python的format函数

作用:格式化输出字符串
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

猜你喜欢

转载自blog.csdn.net/kwoky/article/details/80695464