Python print函式的format()方法的使用
阿新 • • 發佈:2018-11-19
1.使用'{}'佔位符
>>> print("{} {}".format('Hello','world'))
Hello world
>>> print("He is a {} years old boy".format(19))
He is a 19 years old boy
2.使用'{0}' '{1}' 索引形式的佔位符,這種方式可以改變佔位符的位置
>>> print("{0} {1}".format('Hello','world')) Hello world >>> print("{1} {0}".format('Hello','world')) world Hello
3.使用'{name}'形式的佔位符
>>> print('His name is {name}, a {age} years old boy'.format(name='LCF',age='19'))
His name is LCF, a 19 years old boy
4.混合使用索引和名字的形式
>>> print('{0},I\'m {1},{message}'.format('Hello','LCF',message = 'This is a test message!')) Hello,I'm LCF,This is a test message!
5.其他應用
>>> import math >>> print('The value of PI is approximately {}.'.format(math.pi)) The value of PI is approximately 3.141592653589793. >>> print('The value of PI is approximately {!r}.'.format(math.pi)) The value of PI is approximately 3.141592653589793. >>> print('The value of PI is approximately {0:.3f}.'.format(math.pi)) The value of PI is approximately 3.142. >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} >>> for name, phone in table.items(): ... print('{0:10} ==> {1:10d}'.format(name, phone)) ... Sjoerd ==> 4127 Jack ==> 4098 Dcab ==> 7678