python字符串格式化


本文只做简单的记录,不深入研究用法,大牛可移步

使用%

引用:Python基本格式化输出
菜鸟教程-Python 字符串格式化

>>> n1=3.14158
>>> n2=1.2658
>>> print("n1 is %.3f and n2 is %s" % (n1,  n2))
n1 is 3.142 and n2 is 1.2658

函数format

引用:菜鸟教程-Python format 格式化函数
基本语法是通过 {} 和 : 来代替以前的 %

>>> print("n1 is {0} and n2 is {1}".format(n1,n2))
n1 is 3.14158 and n2 is 1.2658
>>> print("n1 is {0:.3f} and n2 is {1}".format(n1,n2))
n1 is 3.142 and n2 is 1.2658

关键字符f或fr

区别:在输出字符串中带有“\”时,必须只能用fr

>>> print(fr"n1 is {n1} and n2 is {n2}")
n1 is 3.14158 and n2 is 1.2658
>>> print(f"n1 is {n1:.3f} and n2 is {n2}")
n1 is 3.142 and n2 is 1.2658

fr表示原生字符串

>>> print(f'D:\project\test.txt')
D:\project      est.txt
>>> print(fr'D:\project\test.txt')
D:\project\test.txt
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值