python的format函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Kwoky/article/details/80695464
作用:格式化输出字符串
age = 25    
name = 'Tom'    
print('{0} is {1} years old. '.format(name, age)) #输出参数   
print('{} is {} years old. '.format(name, age))
#Tom is 25 years old. 
#Tom is 25 years old.


通过关键字参数
print('{name},{age}'.format(age=18,name='Tom'))
#Tom,18


#通过映射 list
a_list = ['Tom',20,'china']
print('my name is {0[0]},from {0[2]},age is {0[1]}'.format(a_list))
#my name is Tom,from china,age is 20


#通过映射 dict
dict = {'name':'Tom','age':20,'country':'Amercia'}
print('my name is {name}, age is {age},from {province}'.format(**dict))
#my name is Tom, age is 20,from Amercia
 
":", 指定代表元素需要的操作
#填充与对齐
print('{:>8}'.format('189'))
#     189
print('{:0>8}'.format('189'))
#00000189
print('{:a>8}'.format('189'))
#aaaaa189
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页