一、格式化字符串
二、代码示例
# 格式化字符串
print("-------------------------------(1)占位符: %------------------------------------")
name = "张三"
age = 20
print("我叫%s,今年%d岁。" % (name, age))
print("-------------------------------(1)% 宽度与精度------------------------------------")
print("%d" % 99)
print("%10d" % 99) # 10表示的是宽度
print("hellohello")
print("%f" % 3.1415926)
print("%.3f" % 3.1415926) # 保留3位小数
print("%10.3f" % 3.1415926) # 同时表示宽度和精度。总宽度是10(小数点也算1位),小数点后3位
print("-------------------------------(2){}------------------------------------")
print("我叫{0},今年{1}岁。".format(name, age))
print("-------------------------------(2){} 宽度与精度------------------------------------")
print("{}".format(3.1415926))
print("{0}".format(3.1415926))
print("{0:.3}".format(3.1415926)) # .3 表示的是一共3位数(小数点不算)
print("{0:.3f}".format(3.1415926)) # .3f 表示的是 3位小数
print("{:.3f}".format(3.1415926)) # .3f 表示的是 3位小数
print("{0:10.3}".format(3.1415926)) # 同时表示宽度和精度。总宽度是10(小数点也算1位),一共3位数
print("{0:10.3f}".format(3.1415926)) # 同时表示宽度和精度。总宽度是10(小数点也算1位),小数点后3位
print("-------------------------------(3)f-string------------------------------------")
print(f"我叫{name},今年{age}岁。")
print(f"{3.1415926}")
运行结果:
D:\Environment\Python\Python311\python.exe D:\Environment\PythonWorks\learnpython\马士兵Python\第9章_一串连一串\P85_84.格式化字符串.py
-------------------------------(1)占位符: %------------------------------------
我叫张三,今年20岁。
-------------------------------(1)% 宽度与精度------------------------------------
99
99
hellohello
3.141593
3.142
3.142
-------------------------------(2){}------------------------------------
我叫张三,今年20岁。
-------------------------------(2){} 宽度与精度------------------------------------
3.1415926
3.1415926
3.14
3.142
3.142
3.14
3.142
-------------------------------(3)f-string------------------------------------
我叫张三,今年20岁。
3.1415926
Process finished with exit code 0
B站视频链接:https://www.bilibili.com/video/BV1wD4y1o7AS?p=85
参考资料:https://blog.csdn.net/weixin_46883785/article/details/133647716