Python中format()方法详解:字符串格式化、数字处理与对齐填充技巧
[id[id_[id_1968531345]522166486]2047493921]

用法:
data-lang="bash">name="Alice"age=30print(.format(name,age))# 位置参数(基本用法)print([id_169721[id_1636675277]57]#关键字参数
这两种形式最后会输出:
My name is Alice and I am 30 years old.
使用示例
1.使用索引
使用索引指定参数位置:
print(
输出:
My name is Alice and I am 30 years old.I repeat,My name is Alice.
[id_1142123546]
foemat()方法能够用于对数字进行格式化操作,其中包括指定小数的位数以及添加千分隔符等。
price=12345.678#保留两位小数:输出“价格是${:.2f}”,其中的价格为 price 进行格式化后的值。#使用千分隔符打印出“价格是 ${:,.2f}”,其中的价格是通过 format 函数格式化后的 price 变量的值。#百分比格式化percentage=0.2567formatted_percentage="{:.2%}".format(percentage)print(formatted_percentage)
输出:
The price is [id_1350368544].68The price is $12,345.625.67%
3.对齐和填充
#左对齐,总宽度为10print("{:<10}".format("Hello"))#右对齐,总宽度为10print("{:>10}".format("Hello"))#居中对齐,总宽度为10print("{:^10}".format("Hello"))#填充字符prinr("{:*^10}".format("Hello"))
输出:
HelloHelloHello**Hello***
4.适用对象属性
#适用对象属性class Person:def_init_(self,name,age):self.name=nameself.age=agePeraon=Person("Charlie",35)formatted_string=.format(person)print(formatted_string)
输出:
My name is Alice and I am 30 years old.
5.使用可迭代对象解包
numbers=(1,2,3)text="Numbers:{0}{1}{2}".format(*numbers)print(text)#输出:Numbers:1 2 3字符串有类似的解包方法,元组也有类似的解包方法,列表同样有类似的解包方法,集合也有类似的解包方法。特别要指出的是,字典类型也有类似的解包方法。numbers={1:10,2:20,3:30}text="Numbers:{0}{1}{2}".format(*numbers.keys())print(text)#输出:Numbers:1 2 3numbers={1:10,2:20,3:30}text="Numbers:{0}{1}{2}".format(*numbers.values())print(text)#输出:Numbers:10 20 30