“b”字符在字符串文本前面做什么?

2024-04-26 23:43:19 发布

您现在位置:Python中文网/ 问答频道 /正文

显然,以下是有效的语法

my_string = b'The string'

我想知道:

  1. 字符串前面的这个b字符是什么意思?
  2. 使用它有什么效果?
  3. 使用它的合适场合是什么?

我在这里找到了一个related question,但是这个问题是关于PHP的,它声明了b用于指示字符串是二进制的,而不是Unicode,这是从PHP<;6版本迁移到PHP 6时代码兼容所需的。我认为这不适用于Python。

我确实在Python站点上找到了this documentation关于使用与Unicode相同语法的u字符来指定字符串。不幸的是,文档中没有提到b字符。

另外,出于好奇,还有比bu更多的符号来做其他事情吗?


Tags: the字符串lt声明stringmyunicode二进制
2条回答

b表示字节字符串。

字节是实际数据。字符串是一种抽象。

如果您有多个字符串对象,并且使用单个字符,则它将是一个字符串,并且根据编码的不同,它的大小可能超过1个字节。

如果将1个字节与一个字节字符串放在一起,您将得到一个从0到255的8位值,如果由于编码而产生的字符是1个字节,则它可能不代表完整的字符。

TBH我会使用字符串,除非我有使用字节的特定低级原因。

引用the Python 2.x documentation

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 documentation声明:

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.

相关问题 更多 >