欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python格式化之format()格式化

程序员文章站 2022-07-15 07:53:10
...

利用format()方法实现字符串格式化

%占位符的方式要刻意区分变量类型,format()方法则无需考虑变量类型

>>> a = 'teacher'
>>> b = 92.3675
>>> print('hello {0}, your score is {1}, good luck for {0}'.format(a,b))
hello teacher, your score is 92.3675, good luck for teacher
>>> 

在{}中也可不指定序号,只要在format()中按顺序指定变量即可

>>> a = 'teacher'
>>> b = 92.3675
>>> print('hello {}, your score is {}, good luck for {}'.format(a,b,a))
hello teacher, your score is 92.3675, good luck for teacher
>>> 

利用format()方法指定小数位数

>>> a = 'teacher'
>>> b = 92.3675
>>> print('hello {}, your score is {:.1f}, good luck for {}'.format(a,b,a))
hello teacher, your score is 92.4, good luck for teacher
>>> 

格式化百分数

>>> 'You score is {0:.1%}'.format(0.8976)   #不指定序号,'You score is {:.1%}'.format(0.8976)
'You score is 89.8%'
>>> 

实现等宽输出

>>> year = 2020
>>> month = 1
>>> day = 4
>>> '{0}-{1:02d}-{2:02d}'.format(year,month,day)  #不指定序号,'{}-{:02d}-{:02d}'.format(year,month,day)
'2020-01-04'
>>> 
相关标签: Python