本文只做简单的记录,不深入研究用法,大牛可移步
使用%
引用: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