显然,以下是有效的语法:
b'The string'
我想知道:
字符串前面的b是什么意思?
使用它的效果是什么?
在什么情况下使用它比较合适?
我在SO上找到了一个相关的问题,但这个问题是关于PHP的,它指出b是用来表示字符串是二进制的,而不是Unicode,这是需要代码从PHP < 6版本兼容,当迁移到PHP 6时。我不认为这适用于Python。
我确实在Python网站上找到了这个文档,是关于使用u字符以相同的语法指定字符串作为Unicode的。不幸的是,该文档中没有任何地方提到b字符。
另外,出于好奇,除了b和u还有别的符号吗?
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)
{“关键”:“价值”}
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()在字符串和字节之间转换。