python字符串格式化—format

基本用法:
>>>"my name is {} and I am {} years old".format("junex",18)
>>>'my name is junex and I am 18 years old'

“{}”相当于占位符,然后调用format()来赋值。如果既想用format(),又想输出“{}”怎么办?

>>>"hello {} and {{}}".format("world")
>>>'hello world and {}'
参数重排

可以用“{index}”的形式来对应format(param0,param1,…)的参数,注意index要从0开始:

>>>"apple is {0}, banana is {1}".format("red","yellow")
>>>'apple is red, banana is yellow'

>>>"apple is {1}, banana is {0}".format("red","yellow")
>>>'apple is yellow, banana is red'

也可以“{参数名}”的方式来对应参数,这样的好处是代码更易读且不需要关心参数的顺序:

>>>"my name is {name} and I am {age} years old".format(age=18,name="junex")
>>>'my name is junex and I am 18 years old'
指定变量类型

这个时候就比较高级了,需要使用{field_name:conversion}的语法,field_name是来指明{}与参数的对应关系的,conversion用来格式化字符串。

#指明数据类型为浮点数
>>>"Today's temperature is {:f} degrees Celsius".format(12)
>>>'Today's temperature is 12.000000 degrees Celsius'

#规定浮点数的精确度
>>>"Today's temperature is {:.3f} degrees Celsius".format(12)
>>>'Today's temperature is 12.000 degrees Celsius'

更多的使用参见官方文档

填充

可以在:(冒号)后跟一个数字来表示参数的占据空间。

>>>"my name is {:20} and I am {:8} years old".format("junex", 18)
>>>"my name is junex                     and I am         18 years old".format("junex", 18)

可以看到字符串是默认左对齐的,数字是默认右对齐。

#左对齐
>>>"{:<10}".format("junex")
>>>'     junex'
#居中
>>>"{:^10}".format("junex")
>>>'  junex   '
#右对齐
>>>"{:>10}".format("junex")
>>>'junex     '

可以看到,python默认使用空格来填充,我们也可以使用自定义的字符来填充:

>>>"{:*^10}".format("junex")
>>>'**junex***'   

使用过程中遇到一个问题:
这里写图片描述
miao
原因是当用0填充时,‘=’会默认使用,然而‘=’只能用于数字。因为‘9’是字符串,所以会报上述错误。
可以使用定位符来解决解决:
999

参考How To Use String Formatters in Python 3 & 官方文档

猜你喜欢

转载自blog.csdn.net/guojunxiu/article/details/79840596