python 格式化字符串 format() 函数
程序员文章站
2022-07-14 17:56:03
...
语法:
通过 {}和 :来替代 %
示例:
通过位置
>>> "{} is {} year old!".format("Jacky", 25)
'Jacky is 25 year old!'
>>> "{0} is {1} year old!".format("Jacky", 25)
'Jacky is 25 year old!'
>>> "{1} is {0} year old!".format("Jacky", 25)
'25 is Jacky year old!'
通过关键字
>>> "{name} is {age} year old!".format(name="Jacky", age=25)
'Jacky is 25 year old!'
通过对象属性
>>> class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "{self.name} is {self.age} year old!".format(self = self)
>>> str(Person("Jacky", 25))
'Jacky is 25 year old!
通过下标
>>> L = ["Jacky", 25]
>>> "{0[0]} is {0[1]} year old!".format(L)
'Jacky is 25 year old!'
格式限定符
>>> "{:>8}".format(2548)
' 2548'
>>> "{:0>8}".format(2548)
'00002548'
>>> "{:*>8}".format(2548)
'****2548'
>>> "{:*^8}".format(2548)
'**2548**'
精度与类型
>>> "{:.2f}".format(3.1415926)
'3.14'
其他类型
>>> "{:b}".format(255) #二进制
'11111111'
>>> "{:d}".format(255) #十进制
'255'
>>> "{:o}".format(255) #八进制
'377'
>>> "{:x}".format(255) #十六进制
'ff'
用,号来做金额的千位分隔符
>>> "{:,}".format(123456789)
'123,456,789'