python 字符串格式化

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

一、%

1 # %d %f %s
2 # %nd n为位置的数量, n>0 正数居右,n<0 正数居左
3 # %f 默认保留小数点后6位,%.nf,n为保留小数点后几位
4 print("%s有%2d个老婆,每个老婆要给%f两" % ("西门庆", 6, 9.9))
5 print("%s有%-2d个老婆,每个老婆要给%.1f两" % ("西门庆", 6, 9.9))

二、format

1、常用格式

1 # 顺序
2 print("我好羡慕{},{}有{}个老婆,每个老婆要给{}两".format("西门庆", "西门庆", 6, 9.9))
3 # 序号
4 print("我好羡慕{0},{0}有{1}个老婆,每个老婆要给{2}两".format("西门庆", 6, 9.9))
5 # 变量 工作最常用
6 print("我好羡慕{name},{name}有{num}个老婆,每个老婆要给{money}两".format(name="西门庆", num=6, money=9.9))
7 # 变量 列表 字典, 注意 字典的key 不加 引号
8 wife = ["潘金莲", "金瓶儿", "李春梅"]
9 print("我好羡慕{name},{name}有{num}个老婆,她们分别是{wife[0]}、{wife[1]}、{wife[2]}".format(name="西门庆", num=3, wife=wife))
10 wife = {"first": "潘金莲", "second": "金瓶儿", "third": "李春梅"}
11 print("我好羡慕{name},{name}有{num}个老婆,她们分别是{wife[second]}、{wife[third]}、{wife[second]}".format(name="西门庆", num=3, wife=wife))

2、填充符号

# 格式 :填充符号 原字符串位置 数量(原字符串数量+填充符号数量)
# 符号 ^ 原字符串居中,< 原字符串居左,> 原字符串居右
# 注意: :原字符串位置 数量(填充字符串数量+原字符串数量) 填充字符串为空
print("{name:*^9}令人羡慕,有{num:>>7}个老婆,家里金银无数,黄金{money:!<6}".format(name="西门庆", num=6, money=100))
print("{name:^5}令人羡慕,有{num:>>3}个老婆,家里金银无数,黄金{money:!<6}".format(name="西门庆", num=6, money=100))

3、数据类型

# :d 整型,  :nd n >0 居右;n <0 居左
# :f 浮点型, :.nf 默认保留小数点后6位,n为保留小数点后几位
# :s 字符串
# :, 表示钱 123,456,789
# :填充符号 原字符位置 数量(填充+原字符) 字符格式(nd .nf s ,)
# 注意 无填充符号,则为空字符串
print("{name}今年赚了{make_money}元,存多少{save_money}元".format(name="小明", make_money="100", save_money="9.9"))
# 错误 数据类型错误 ValueError: Unknown format code 'd' for object of type 'str'
# print("{name:s}今年赚了{make_money:4d}元,存多少{save_money:.2f}元".format(name="小明", make_money="100", save_money="9.9"))
print("{name:s}今年赚了{make_money:4d}元,存多少{save_money:.2f}元".format(name="小明", make_money=100, save_money=9.9765))
val = "{name:^6s}今年赚了{make_money:^6d}元,存多少{save_money:-^10.2f}元,为公司贡献{money:~>10,}元".\
format(name="小明", make_money=100, save_money=9.9765, money=123456)
print(val)

 



阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: python