Python--format()学习记录

.format():格式化输出字符串

示例:

age = 25  
name = 'Caroline'  
  
print('{0} is {1} years old. '.format(name, age)) #输出参数  
print('{0} is a girl. '.format(name))  
print('{0:.3} is a decimal. '.format(1/3)) #小数点后三位  
print('{0:_^11} is a 11 length. '.format(name)) #使用_补齐空位  
print('{first} is as {second}. '.format(first=name, second='Wendy')) #别名替换  
print('My name is {0.name}'.format(open('out.txt', 'w'))) #调用方法  

输出:

Caroline is 25 years old.   
Caroline is a girl.   
0.333 is a decimal.   
_Caroline__ is a 11 length.   
Caroline is as Wendy.   
My name is out.txt  

增补知识点:

填充与对齐
填充常跟对齐一起使用
^、<、>分别是居中、左对齐、右对齐,后面带宽度
:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
比如

In [15]: '{:>8}'.format('189')
Out[15]: '     189'
In [16]: '{:0>8}'.format('189')
Out[16]: '00000189'
In [17]: '{:a>8}'.format('189')
Out[17]: 'aaaaa189'

欢迎留言交流!

猜你喜欢

转载自blog.csdn.net/qq_38251616/article/details/79763695