python - r"string"b"string"u"string"Python 2/3 比较

标签 python python-3.x string python-2.7

我已经知道 Python 2.7 中的 r"string" 通常用于正则表达式模式。我还看到 u"string" 我认为是 Unicode 字符串。现在使用 Python 3 我们可以看到 b"string"

我在不同的来源/问题中搜索了这些,例如 What does a b prefix before a python string mean? ,但是很难在 Python 中看到所有这些带前缀的字符串的全貌,尤其是在 Python 2 和 3 中。

问题:您是否有一条经验法则来记住 Python 中带有前缀的不同类型的字符串?(或者可能是一个包含 Python 2 列和 Python 3 列的表格?)

注意:我已经阅读了一些问题和答案,但我没有找到一个容易记住的与所有前缀/Python 2+3 的比较

最佳答案

来自文字的 python 文档:https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

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.

Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters. As a result, in string literals, '\U' and '\u' escapes in raw strings are not treated specially. Given that Python 2.x’s raw unicode literals behave differently than Python 3.x’s the 'ur' syntax is not supported.

A string literal with 'f' or 'F' in its prefix is a formatted string literal; see Formatted string literals. The 'f' may be combined with 'r', but not with 'b' or 'u', therefore raw formatted strings are possible, but formatted bytes literals are not.

所以:

  • r 表示原始
  • b 表示字节数
  • u 表示unicode
  • f 表示格式

rb 已经在 Python 2 中可用,在许多其他语言中也是如此(它们有时非常方便)。

由于字符串文字在 Python 2 中不是 unicode,因此创建了 u 字符串以提供对国际化的支持。从 Python 3 开始,u 字符串是默认字符串,因此“...”在语义上与 u“...”相同。

最后,从中可以看出,f 字符串是 Python 2 中唯一不支持的字符串。

关于python - r"string"b"string"u"string"Python 2/3 比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54533637/

相关文章:

python - 使用 map/reduce 添加列表中一对数字的差异

python - 生成随机 DNA 序列

Python3 - 如何正确地进行绝对导入并让 Pylint 开心

Python-tkinter : Opening and closing dialog windows

python - Sqlalchemy 按列表中的字段过滤但保持原始顺序?

python - 在 asyncio sleep 期间检查新的控制命令

python - 使用 Python 的内置 .csv 模块编写

c - 你好,我正在编写一个 C 程序来获取给定字符串中字符的位置

java - 高效且干净地解析 JSON 字符串

string - python 修改内置字符串函数