python 输出表达式之format

转载请注明:博客的来源,谢谢!
principal = 1000 rate = 0.05 numyears = 5 year = 1 while year <= numyears: principal = principal * ( 1 + rate ) print( year , principal) year += 1
#输出:

python express.py
(1, 1050.0)
(2, 1102.5)
(3, 1157.625)
(4, 1215.5062500000001)
(5, 1276.2815625000003)

#将 print( year , principal)替换成 print( format(year,'3d'),format(principal,'0.2f'))

#输出

python express.py
(' 1', '1050.00')
(' 2', '1102.50')
(' 3', '1157.62')
(' 4', '1215.51')
(' 5', '1276.28')

format('要输出的内容','格式')
#还可以
#将 print( year , principal)替换成 print('{0:3d} {1:0.2f}'.format(year,principal))

python express.py
1 1050.00
2 1102.50
3 1157.62
4 1215.51
5 1276.28#print('{0:3d} {1:0.2f}'.format(year,principal)):号前面的0表示year第一个位置,:号前面的1表示princpal第二个位置,:号后面的代表格式

#字典格式输出

List = {'Name': 'xiaowei', 'Age': 23, 'Job': 'Python'}
print('Name: {0[Name]:s}; Age: {0[Age]:d}; ''Job: {0[Job]:s}'.format(List))

#输出

#Name: xiaowei; Age: 23; Job: Python

 

##################################################################

#此外还可以

print('{year} {principal}'.format(year=12,principal=3))

#结果

#python express.py
#12 3

#############################################################

>>> a = "My name is {0},and my age is {age}"   {0},{1}作为占位符用,{age}字典式的用法
>>> a.format('wei',age=22)
'My name is wei,and my age is 22'

 

 

你可能感兴趣的:(python 输出表达式之format)