今天来学习字符串格式化
Python字符串格式化 % 用格式化符号% 进行格式化字符串时,Python使用一个字符串作为模板。模板中有格式符,这些格式符为真实值预留位置,并说明真实数值应该呈现的格式。Python用一个tuple将多个值传递给模板,每个值对应一个格式符。
1 2 >>> print("%s has %d dollars" % ('Tom' , 200 ))Tom has 200 dollars
当我们的模板中含有过多的格式符时,仅仅依靠格式符的顺序传入真实值,有可能会出现衣服扣子扣错位置的现象
1 2 3 4 >>> print("%s is %d years old and %s was born in %s" % ('Tom' , '15' , 'Sanfrancisco' ))Traceback (most recent call last): File "<stdin>" , line 1 , in <module> TypeError: %d format: a number is required, not str
为了避免这种现象,我们可以给格式符指定名称,用字典来传递真实值
1 2 >>> print("%(name1)s is %(age)d years old and %(name2)s was born in %(place)s" % {'name1' : 'Tom' , 'age' : 15 , 'name2' : 'Alice' , 'place' : 'Sanfrancisco' })Tom is 15 years old and Alice was born in Sanfrancisco
除了%d和%s外,还有如下字符串格式符的类型码
格式符
类型
%s
字符串
%c
单个字符
%d, %i
十进制整数
%o
八进制整数
%x
十六进制整数
%f
浮点数
%e
指数(e为底)
除此之外,我们还可以对格式符的格式进行控制,模板:%[(name)][flags][width].[precision]typecode
1 2 3 4 >>> print("%.3f" % 3.1415926 )3.142 >>> print("%03d" % 1 )001
相对基本格式化输出采用‘%’的方法,format功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’
该函数提供了多种位置匹配方式
1 2 >>> print("My name is {}" .format('Jerry' ))My name is Jerry
1 2 >>> print("{0} is {1} years old" .format('Tom' , 12 ))Tom is 12 years old
1 2 >>> print("{name} is {age} years old" .format(name='Tom' , age=12 ))Tom is 12 years old
1 2 3 >>> list = ['Tom' , 12 ]>>> print("{l[0]} is {l[1]} years old" .format(l=list))Tom is 12 years old
1 2 3 >>> dict = {'name' : 'Tom' , 'age' : 12 }>>> print("{d[name]} is {d[age]} years old" .format(d=dict))Tom is 12 years old
和%不同的是,format函数不需要提前指定真实值的类型,这样的设定更符合python语言的特性,且使用起来更加方便,当我们需要格式化输出指定的内容时,只需要在{}里添加内容即可
1 >>> print("{:.3f}" .format(3.1415926 ))
1 2 >>> print("{:b}" .format(2 ))10
1 2 >>> print("{:x}" .format(15 ))f
其他功能
1 2 3 4 >>> from datetime import datetime>>> now = datetime.now()>>> print('{:%Y-%m-%d %X}' .format(now))2020 -01 -19 22 :39 :51
format函数定义的字符串模板还可以当做函数使用
1 2 3 >>> print_fnc = "{} is the biggest company in the world" .format >>> print_fnc('Apple' )'Apple is the biggest company in the world'