python字符串的概念_Python 中的字符串前缀

一直以来,在 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

F-String 实例

>>> 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" '

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值