Python 2.6+中,format()
是一个非常强大的函数,可以帮助我们填充、格式化字符串。
语法
- 字符串中,使用
{}
包含需要替代的部分,未被{}
包含的表示要显示的文字。如果要显示的文字中包含{}
,应使用{{}}
填充
通过位置填充
指定填充位置
填充的地方用{position}
表示,format()
接受多个字符串作为参数。
>>> "Hello {0}! I am {1}".format("World", "Sue")
'Hello World! I am Sue'
>>> "Between {0} and {1}, I prefer {0}.".format("Apple", "Banana")
'Between Apple and Banana, I prefer Apple.'
未指定填充位置
填充的地方用{}
表示,format()
接受多个字符串作为参数。
>>> "Hello {}! I am {}".format("World", "Sue")
'Hello World! I am Sue'
通过关键字填充
填充的地方用{key}
表示,format()
接受多个键值对作为参数。
>>> "Between {fruit1} and {fruit2}, I prefer {fruit1}.".format(fruit1="Apple", fruit2="Banana")
'Between Apple and Banana, I prefer Apple.'
通过数组下标填充
填充的地方用{position[index]}
或{key[index]}
表示,format()
接受字符串数组作为参数。
>>> "Hello {0[0]}! I am {0[1]}".format(["World","Sue"])
'Hello World! I am Sue'
>>> "Hello {names[0]}! I am {names[1]}. I am in {addresses[1]}, {addresses[0]}".format(names=["World","Sue"], addresses=["China","Shanghai"])
'Hello World! I am Sue. I am in Shanghai, China'
通过字典key
>>> "Between {fruits[fruit1]} and {fruits[fruit2]}, I prefer {fruits[fruit1]}.".format(fruits={"fruit1":"Apple", "fruit2":"Banana"})
'Between Apple and Banana, I prefer Apple.'
通过对象的属性填充
>>> class Fruits():
... fruit1 = "Apple"
... fruit2 = "Banana"
...
>>> "Between {fruits.fruit1} and {fruits.fruit2}, I prefer {fruits.fruit1}.".format(fruits=Fruits)
'Between Apple and Banana, I prefer Apple.'
使用*
**
关于*
**
如何使用,可参考Python 参数
>>> args = ["Sue", "Bob"]
>>> kargs = {"language":"English", "hobby":"Swimming"}
>>> print("{0} and {1} speak {language} and love {hobby}".format(*args, **kargs))
Sue and Bob speak English and love Swimming
替换
格式化
对齐
通过以下形式实现对齐:
{0:[填充字符][对齐方式 <^>][宽度]}
比如:
>>> '{0:*>20}'.format(10)
'******************10'
>>> '{0:*<20}'.format(10)
'10******************'
>>> '{0:*^20}'.format(10)
'*********10*********'