一、自定义格式
1.利用占位符{}
print("{}_{}".format("Hello","world"))
#结果
Hello_world
2.利用带有顺序的占位符{}
print("{0}-{2}-{1}".format("Hello!","day","good"))
#结果
Hello!-good-day
3.利用带有关键字的占位符{}
print("Good morning {name}".format(name="Lili"))
#结果
Good morning Lili
二、访问字典的值
person={"name":"Lili","age":20}
print("Name:{name},Age:{age}".format(**person))
#结果
Name:Lili,Age:20
三、格式化数字
1.格式化小数点后的位数::.nf(n为要保留小数点的个数)
print("{:.2f}".format(3.1415926))
#结果
3.14
2.格式化输出整数:
① :.0f(保留0位小数)
print("{:.0f}".format(3.1415926))
#结果
3
② :d(只能用于整数)
print("{:d}".format(3))
#结果
3
3.千位分隔符::,
print("{:,}".format(12345.7))
#结果
12,345.7
4.百分比::n%
print("{:.2%}".format(0.25647))
#结果
25.65%
5.指数表示:
① :e
print("{:e}".format(123456789.78))
#结果
1.234568e+08
② :E
print("{:E}".format(123456789.78))
#结果
1.234568E+08
四、字符串的对齐方式和填充格式
1.左对齐::<width
print("{:<10}".format("left"))
#结果
left ”
2.右对齐::>width
print("{:>10}".format("right"))
#结果
right”
3.居中对齐::^width
print("{:^10}".format("center"))
#结果
center ”
4.填充字符::字符<(>\^)width
print("{:!>10}".format("fill"))
#结果
!!!!!!fill”
五、自定义格式格式化时间
from datetime import datetime
now=datetime.now()
print("{:%Y-%m-%d %H:%M:%S}".format(now))
#结果
2024-12-26 11:19:42
六、使用f-string
name="Lili"
age=20
print(f"Name={name},Age={age}")
#结果
Name=Lili,Age=20