問題描述
顯然,以下是有效的語法:
Apparently, the following is the valid syntax:
my_string = b'The string'
我想知道:
- 字符串前面的這個
b
字符是什么意思? - 使用有什么效果?
- 在什么情況下使用合適?
我在 SO 上找到了一個相關問題,但這個問題是關于 PHP 的,它說明了 b
用于指示字符串是二進制的,與 Unicode 不同,Unicode 是與 PHP 版本兼容所必需的.6,遷移到 PHP 6 時.我認為這不適用于 Python.
I found a related question right here on SO, but that question is about PHP though, and it states the b
is used to indicate the string is binary, as opposed to Unicode, which was needed for code to be compatible from version of PHP < 6, when migrating to PHP 6. I don't think this applies to Python.
我確實在 Python 網站上找到了關于使用u
字符以相同的語法將字符串指定為 Unicode.不幸的是,它沒有在該文檔的任何地方提及 b 字符.
I did find this documentation on the Python site about using a u
character in the same syntax to specify a string as Unicode. Unfortunately, it doesn't mention the b character anywhere in that document.
另外,出于好奇,有沒有比 b
和 u
更多的符號來做其他事情?
Also, just out of curiosity, are there more symbols than the b
and u
that do other things?
推薦答案
引用 Python 2.x 文檔:
'b' 或 'B' 的前綴在蟒蛇2;它表明文字應該成為字節文字在 Python 3 中(例如,當代碼用 2to3 自動轉換).一個'u' 或 'b' 前綴可以后跟'r' 前綴.
A prefix of 'b' or 'B' is ignored in Python 2; it indicates that the literal should become a bytes literal in Python 3 (e.g. when code is automatically converted with 2to3). A 'u' or 'b' prefix may be followed by an 'r' prefix.
Python 3 文檔 指出:
字節文字總是以'b'或'B'為前綴;它們生成 bytes 類型而不是 str 類型的實例.它們可能只包含 ASCII 字符;數值為 128 或更大的字節必須用轉義符表示.
Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.
這篇關于字符串文字前面的“b"字符有什么作用?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!