赞
踩
我是精神抖擞王大鹏,不卑不亢,和蔼可亲~
计算机硕士,目前小米大数据开发。日常会分享总结一些自己面试实际问题的回答,欢迎一起讨论。
公众号: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'
f"{{ {10 * 8} }}"
'{ 80 }'
f"{{ 10 * 8 }}"
'{ 10 * 8 }'
"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'
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。