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

b'The string'

我想知道:

字符串前面的b是什么意思? 使用它的效果是什么? 在什么情况下使用它比较合适?

我在SO上找到了一个相关的问题,但这个问题是关于PHP的,它指出b是用来表示字符串是二进制的,而不是Unicode,这是需要代码从PHP < 6版本兼容,当迁移到PHP 6时。我不认为这适用于Python。

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

另外,出于好奇,除了b和u还有别的符号吗?


当前回答

它将其转换为bytes字面值(或2.x中的str),并且对2.6+有效。

r前缀导致反斜杠“未解释”(不会被忽略,两者之间的差异很重要)。

其他回答

下面是一个例子,在Python 3.x中,缺少b将抛出TypeError异常

>>> f=open("new", "wb")
>>> f.write("Hello Python!")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface

加上一个b前缀就能解决这个问题。

Bytes (somestring.encode())是在python 3中为我工作的解决方案。

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()

从服务器端,如果我们发送任何响应,它将以字节类型的形式发送,因此它将在客户端显示为b' response From server'

为了消去b'....'只需使用下面的代码:

服务器文件:

stri="Response from server"    
c.send(stri.encode())

客户端文件:

print(s.recv(1024).decode())

然后打印Response from server

b"hello" is not a string (even though it looks like one), but a byte sequence. It is a sequence of 5 numbers, which, if you mapped them to a character table, would look like h e l l o. However the value itself is not a string, Python just has a convenient syntax for defining byte sequences using text characters rather than the numbers itself. This saves you some typing, and also often byte sequences are meant to be interpreted as characters. However, this is not always the case - for example, reading a JPG file will produce a sequence of nonsense letters inside b"..." because JPGs have a non-text structure.

.encode()和.decode()在字符串和字节之间转换。

您可以使用JSON将其转换为字典

import json
data = b'{"key":"value"}'
print(json.loads(data))

{“关键”:“价值”}


瓶:

这是一个flask的例子。在终端行上运行:

import requests
requests.post(url='http://localhost(example)/',json={'key':'value'})

瓶/ routes.py

@app.route('/', methods=['POST'])
def api_script_add():
    print(request.data) # --> b'{"hi":"Hello"}'
    print(json.loads(request.data))
return json.loads(request.data)

{“关键”:“价值”}