Python的f-strings格式化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29027865/article/details/84850683

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

猜你喜欢

转载自blog.csdn.net/qq_29027865/article/details/84850683