Python格式化之f_string格式化

利用f_string实现字符串格式化(python3.6之后的版本新增)

在字符串的前面加上f前缀,并将变量名称用大括号括起来,Python就可以自动识别并引用变量

#其他前缀
>>> b'hello'
b'hello'
>>> bytes
<class 'bytes'>

>>> r'c:\windows\files'
'c:\\windows\\files'
>>> r'/etc/passwd'
'/etc/passwd'
>>> 

#在字符串的前面加上f前缀,并将变量名称用大括号括起来,Python就可以自动识别并引用变量
>>> a = 'teacher'
>>> b = 92.3675
>>> f'hello {a} ,your score is {b}'
'hello teacher ,your score is 92.3675'
>>> 

利用f_string指定小数位数

>>> a = 'teacher'
>>> b = 92.3675
>>> f'hello {a} ,your score is {b}'
'hello teacher ,your score is 92.3675'
>>> 
>>> 
>>> f'hello {a} ,your score is {b:.1f}'
'hello teacher ,your score is 92.4'
>>> 

实现等宽输出

>>> year = 2020
>>> month = 1
>>> day = 4  
>>> 
>>> f'{year}-{month:02d}-{day:02d}'
'2020-01-04'
>>> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值