在字符串字面量前面加上'b'字符是什么意思?

1377

显然,以下是有效的语法:

b'The string'

我想知道:

  1. 在字符串前面加上这个b字符是什么意思?
  2. 使用它有什么影响?
  3. 何时适合使用它?

我在这里的SO相关问题中发现了一个相关的问题,但那个问题是关于PHP的,它说明 b用来表示字符串是二进制的,而不是Unicode的,在从PHP版本<6迁移到PHP 6时需要兼容。 我认为这不适用于Python。

我在Python网站上找到了关于使用相同语法中的u字符指定Unicode字符串的文档。不幸的是,该文档没有提及在该文档中的任何地方都没有b字符。

另外,只是出于好奇,是否存在比bu更多功能的符号?


4
自Python 3.6版本以来,有一种非常有用的f-strings字符串格式化方法可供使用。例如,您可以通过以下方式打印出“Hello world”这个字符串:v = "world" print(f"Hello {v}")。还可以通过f"{2 * 5}"这种方式得到字符串"10"。使用f-strings是处理字符串的一种更好的方式。 - thanos.a
3
f-Strings还有一个很方便的调试功能,如果在变量后面但括号前面加上等号(=),就会输出“v=123”字符串,以显示正在打印的任何内容的名称。即使是表达式,所以f'{25=}'也会输出"25=10"。 - diamondsea
1
@diamondsea,该功能是在3.8版本中引入的。 - AcK
对于好奇心的部分:stringprefix :: = "r" | "u" | "R" | "U" | "f" | "F" | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"bytesprefix::= "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"。[文档:字符串和字节文字](https://docs.python.org/3/reference/lexical_analysis.html#literals) - AcK
@thanos.a 这就是方法... - Eric Nelson
12个回答

1

在Python 3中,bytes(somestring.encode())是解决我的问题的方法。

def compare_types():
    output = b'sometext'
    print(output)
    print(type(output))


    somestring = 'sometext'
    encoded_string = somestring.encode()
    output = bytes(encoded_string)
    print(output)
    print(type(output))


compare_types()

1
回答问题1和2:b表示您想将普通的String类型转换/利用为Byte类型。举个例子:
>>> type(b'')
<class 'bytes'>
>>> type('')
<class 'str'> 

回答问题3:当我们想要检查某个文件/对象的字节流(一系列字节)时,可以使用它。也就是说,我们想要检查某个文件的SHA1消息摘要。
import hashlib

def hash_file(filename):
   """"This function returns the SHA-1 hash of the file passed into it"""

   # make a hash object
   h = hashlib.sha1()

   # open file for reading in binary mode
   with open(filename,'rb') as file:

       # loop till the end of the file
       chunk = 0
       while chunk != b'':
           # read only 1024 bytes at a time
           chunk = file.read(1024)
           h.update(chunk)

   # return the hex representation of digest
   return h.hexdigest()

message = hash_file("somefile.pdf")
print(message)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接