format()方法(python)

一、自定义格式

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值