Python的f-strings格式化

我是精神抖擞王大鹏,不卑不亢,和蔼可亲~
计算机硕士,目前小米大数据开发。日常会分享总结一些自己面试实际问题的回答,欢迎一起讨论。
公众号:diting_dapeng

'f-strings’是Python的一种新的字符串格式化方法,要使用f-strings,只需在字符串前加上f,语法格式如下:

f ' <text> { <expression> <optional !s, !r, or !a> <optional : format specifier> } <text> ... '

基本用法

name = "Tom"
age = 3
f"His name is {name}, he's {age} years old."
"His name is Tom, he's 3 years old."

实质上,把括号内的当作是变量即可。

支持表达式

# 数学运算
f'He will be { age+1 } years old next year.'
'He will be 4 years old next year.'

# 对象操作
spurs = {"Guard": "Parker", "Forward": "Duncan"}
f"The {len(spurs)} players are: {spurs['Guard']} the guard, and {spurs['Forward']} the forward."
'The 2 players are: Parker the guard, and Duncan the forward.'

f'Numbers from 1-10 are {[_ for _ in range(1, 11)]}'
'Numbers from 1-10 are [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'

数字操作

# 小数精度
PI = 3.141592653
f"Pi is {PI:.2f}"
'Pi is 3.14'

# 进制转换
f'int: 31, hex: {31:x}, oct: {31:o}'
'int: 31, hex: 1f, oct: 37'

与原始字符串联合使用(使其没有转义字符)

fr'hello\nworld'
'hello\\nworld'

注意事项

  1. {}内不能包含反斜杠\,但可以使用不同的引号,或使用三引号。使用引号是将不再表示一个变量,而是当作了字符串来处理。
  2. 如何插入大括号?
f"{{ {10 * 8} }}"
'{ 80 }'
f"{{ 10 * 8 }}"
'{ 10 * 8 }'
  1. 使用str.format(),非数字索引将自动转化为字符串,而f-strings则不会
"Guard is {spurs[Guard]}".format(spurs=spurs)
'Guard is Parker'

f"Guard is {spurs[Guard]}"
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    f"Guard is {spurs[Guard]}"
NameError: name 'Guard' is not defined

f"Guard is {spurs['Guard']}"
'Guard is Parker'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

精神抖擞王大鹏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值