本文主体翻译自油管视频:https://www.youtube.com/watch?v=EoNOWVYKyo0&list=LL&index=2&t=438s
https://www.youtube.com/watch?v=aa39jL7wdJs
在Python中,f-strings是一种字符串格式化方法,允许通过 { } 加入变量。使用方法大致为:
f'string string string {变量:格式化方法} string string '
下面介绍五种实用方法:
1. 整数千分位符
想要输出类似1,000,000的数据,可以用 f' {变量:分位符} ' 的方式
示例:
print(f'n={n:_}')
#输出: n=100_000_000
print(f'n={n:,}')
#输出:n=100,000,000
2. 字符串对其方式
可以通过 占位符(默认为空格)+ <或>或^ 决定输出对齐方式
示例
#:占位符(默认空格)对其方式+长度
var: str = 'string'
print(f':{var:_>20}:')
#输出::______________string:
print(f':{var:#<20}:')
#输出::string##############:
print(f':{var:^20}:')
#输出: : string
3. 浮点数精度输出:
通过 . +小数位数+ f 定义输出的小数位数,类似round(n)
示例:
#浮点数精度
n: float=12345.67891
print(f'n is {n:.2f}')
#输出: n is 12345.68
print(f'n is {n:.2e}')
#输出 n is 1.23e+04
print(f'n is :{n:^20_.3f}:')
#输出:n is 12_345.679
4. 日期格式化输出:
通过%m, %y , %c ...等格式话方式决定输出格式。格式化方式很多,只要记住常见的年月日时分秒即可, 至于其他的建议需要用到再查询
可以参考python中各种时间格式的转换 - 知乎 (zhihu.com)
from datetime import datetime
now: datetime = datetime.now()
print(f'now is: {now:%d.%m.%y (%H:%M:%S)}')
#输出: now is: 21.03.24 (20:17:11)
print(f'now is: {now: %c}')
#输出: now is: Thu Mar 21 20:17:11 2024
print(f'now is: {now:%I%p}')
#输出: now is: 08PM
5. 通过 = 进行计算,再格式化输出 (常用于debug)
通过{ 式子 = }的形式,python会先对式子进行计算,再将式子和结果作为字符串整体输出
你同样可以在 = 后面加入 : +格式化方式 来对结果输出格式化
例子:
a: int = 5
b: int =10
my_var: str = 'hello world'
print(f'{a + b = }')
#输出: a + b = 15
print(f'{bool(a) = }')
#输出: bool(a) = True
print(f'{my_var = }')
#输出: my_var = 'hello world'
print(f'{my_var = !s}')
#!s表示去除冒号输出
#输出:my_var = hello world
print(f'{my_var =:_^20}')
#输出:my_var =____hello world_____
6. 和r-string结合
不多解释了,看例子更清楚:
folder_name= 'Folder Name'
path = rf"C:\test\test\{folder_name}"
print(path)
#输出:C:\test\test\Folder Name
所有代码合集:
n: int = 100000000
print(f'n={n:_}')
#输出: n=100_000_000
print(f'n={n:,}')
#输出:n=100,000,000
#align
#:占位符(默认空格)对其方式+长度
var: str = 'string'
print(f':{var:_>20}:')
#输出::______________string:
print(f':{var:#<20}:')
#输出::string##############:
print(f':{var:^20}:')
#输出: : string :
#日期输出
from datetime import datetime
now: datetime = datetime.now()
print(f'now is: {now:%d.%m.%y (%H:%M:%S)}')
#输出: now is: 21.03.24 (20:17:11)
print(f'now is: {now: %c}')
#输出: now is: Thu Mar 21 20:17:11 2024
print(f'now is: {now:%I%p}')
#输出: now is: 08PM
#浮点数精度
n: float=12345.67891
print(f'n is {n:.2f}')
#输出: n is 12345.68
print(f'n is {n:.2e}')
#输出 n is 1.23e+04
print(f'n is :{n:^20_.3f}:')
#输出:n is 12_345.679
a: int = 5
b: int =10
my_var: str = 'hello world'
print(f'{a + b = }')
#输出: a + b = 15
print(f'{bool(a) = }')
#输出: bool(a) = True
print(f'{my_var = }')
#输出: my_var = 'hello world'
print(f'{my_var = !s}')
#!s表示去除冒号输出
#输出:my_var = hello world
print(f'{my_var =:_^20}')
#输出:my_var =____hello world_____
folder_name= 'Folder Name'
path = rf"C:\test\test\{folder_name}"
print(path)
#输出:C:\test\test\Folder Name