Format函式—字串格式化
Format函式:
作用:格式化輸出字串
格式:
‘’.format(value[,format_spec=’ ‘])
示例:
#位置匹配
>>> sun = ‘sunhziwen’
>>> s =43
>>> ‘my name is {}.’.format(sun)
‘my name is sunhziwen.’
>>> ‘my name is {1},I’m {0} years old.’.format(s,sun)
“my name is sunhziwen,I’m 43 years old.”
#關鍵字或字典
>>> s = {‘name’:‘sunzhiwen’, ‘age’:25}
>>> ‘my name is {name},I’m {age} years old.’.format(s) #字典
“my name is sunzhiwen,I’m 25 years old.”
>>> ‘my name is {name},I’m {age} years old.’.format(name=‘sunzhiwen’,age=23)
“my name is sunzhiwen,I’m 23 years old.”
#對齊
>>> print(’{:^14}’.format(“sunzhiwen”))
sunzhiwen
>>> print(’{:>14}’.format(“sunzhiwen”))
sunzhiwen
>>> print(’{:>14}’.format(“sunzhiwen”))
*****sunzhiwen
>>> print(’{:<14}’.format(“sunzhiwen”))
sunzhiwen
>>> print(’{:<14}’.format(“sunzhiwen”))
sunzhiwen
#精度:
>>> print(’{:.4f}’.format(3.14))
3.1400
>>> print(’{:.4f}’.format(3.141592656469))
3.1416
#進位制轉換
>>> print(’{:b}’.format(250))
11111010
>>> print(’{