一直以来,在 Python 中用字符串的时候前面会加上 "u","r","f" 等前缀,当然用的时候会去查是什么意思,但总觉得应该了解一下 Python 中所有的前缀有哪些。于是翻了翻官方文档,在介绍常量类型的地方有写。大概看了看,总结一下。
前缀的含义
首先是所有支持的前缀有 "r" | "u" | "R" | "U" | "f" | "F" | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF" 这些。这应该是3.6版本之后的情况,因为 "f" 是3.6版引入的。这其中有一些两个字母的前缀,当然就是同时生效的意思。而大写和小写其实是一样的,所以其实一共只需弄懂 "r" | "u" | "f" 三种即可。
前缀 | 含义 |
---|---|
"r" | Raw string,就是原始字符串,忽略转义字符 |
"u" | Unicode string,是指用 unicode 编码存储字符串 |
"f" | Formatted string,格式化字符串 |
一些说明
- 在 Python3 中字符串默认即用 unicode 存储,所以 Python3 中前缀 " u" 其实没有用,现在主要用于编写兼容 Python2 的代码。
- 前缀 "f" 在 Python3.6 中引入,是一种新的格式化字符串的方式,在字符串中用 {} 包裹表达式,非常好用。如需输出 { 或 } 则需要输入 {{ 或 }}
转义字符
Escape Sequence | Meaning |
---|---|
\newline | Backslash and newline ignored |
\ | Backslash () |
\' | Single quote (') |
\" | Double quote (") |
\a | ASCII Bell (BEL) |
\b | ASCII Backspace (BS) |
\f | ASCII Formfeed (FF) |
\n | ASCII Linefeed (LF) |
\r | ASCII Carriage Return (CR) |
\t | ASCII Horizontal Tab (TAB) |
\v | ASCII Vertical Tab (VT) |
\ooo | Character with octal value ooo |
\xhh | Character with hex value hh |
\N{name} | Character named name in the Unicode database |
\uxxxx | Character with 16-bit hex value xxxx |
\Uxxxxxxxx | Character with 32-bit hex value xxxxxxxx |
其中 \N{name} 支持的 name 见 http://www.unicode.org/Public/11.0.0/ucd/NameAliases.txt
F-String 实例
F-String,即前缀 "f" 的字符串在网上已有很多教程,这里贴一下官方文档中的示例。具体参见 https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals
>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is 'Fred'."
>>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
"He said his name is 'Fred'."
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
'result: 12.35'
>>> today = datetime(year=2017, month=1, day=27)
>>> f"{today:%B %d, %Y}" # using date format specifier
'January 27, 2017'
>>> f"{today=:%B %d, %Y}" # using date format specifier and debugging
'today=January 27, 2017'
>>> number = 1024
>>> f"{number:#0x}" # using integer format specifier
'0x400'
>>> foo = "bar"
>>> f"{ foo = }" # preserves whitespace
" foo = 'bar'"
>>> line = "The mill's closed"
>>> f"{line = }"
'line = "The mill\'s closed"'
>>> f"{line = :20}"
"line = The mill's closed "
>>> f"{line = !r:20}"
'line = "The mill\'s closed" '