python格式化输出

1、打印字符串

>>> print ("His name is %s"%("Aviad"))
His name is Aviad

2.打印整数

>>> print ("He is %d years old"%(25))
He is 25 years old

3.打印浮点数

>>> print ("His height is %f m"%(1.83))
His height is 1.830000 m

4.打印浮点数(指定保留小数点位数)

>>> print ("His height is %.2f m"%(1.83))
His height is 1.83 m

5.指定占位符宽度

>>> print ("Name:%10s Age:%8d Height:%8.2f"%("Aviad",25,1.83))
Name:     Aviad Age:      25 Height:    1.83

6.指定占位符宽度(左对齐)

>>> print ("Name:%-10s Age:%-8d Height:%-8.2f"%("Aviad",25,1.83))
Name:Aviad      Age:25       Height:1.83 

7.指定占位符(只能用0当占位符?)

>>> print ("Name:%-10s Age:%08d Height:%08.2f"%("Aviad",25,1.83))
Name:Aviad      Age:00000025 Height:00001.83
>>> print("1/3 equal %.3f %%" % (33.33333))
1/3 equal 33.333 %

8.%%

>>> print("1/3 equal %.3f %%" % (33.33333))
1/3 equal 33.333 %

9.科学计数法

>>> format(0.0015,'.2e')
'1.50e-03'

python之字符串格式化(format)

用法: 它通过{}和:来代替传统%方式

1、使用位置参数

要点:从以下例子可以看出位置参数不受顺序约束,且可以为{},只要format里有相对应的参数值即可,参数索引从0开,传入位置参数列表可用*列表

>>> li = ['hoho',18]
>>> 'my name is {} ,age {}'.format('hoho',18)
'my name is hoho ,age 18'
>>> 'my name is {1} ,age {0}'.format(10,'hoho')
'my name is hoho ,age 10'
>>> 'my name is {1} ,age {0} {1}'.format(10,'hoho')
'my name is hoho ,age 10 hoho'
>>> 'my name is {} ,age {}'.format(*li)
'my name is hoho ,age 18'

2、使用关键字参数

要点:关键字参数值要对得上,可用字典当关键字参数传入值,字典前加**即可

>>> hash = {'name':'hoho','age':18}
>>> 'my name is {name},age is {age}'.format(name='hoho',age=19)
'my name is hoho,age is 19'
>>> 'my name is {name},age is {age}'.format(**hash)
'my name is hoho,age is 18'

3、填充与格式化

:[填充字符][对齐方式 <^>][宽度]

>>> '{0:.2f}'.format(1 / 3)
'0.33'
>>> '{0:b}'.format(10)    #二进制
'1010'
>>> '{0:o}'.format(10)     #八进制
'12'
>>> '{0:x}'.format(10)    #16进制 
'a'
>>> '{:,}'.format(12369132698)  #千分位格式化
'12,369,132,698'

4、精度与进制

>>> '{0:.2f}'.format(1/3)
'0.33'
>>> '{0:b}'.format(10)    #二进制
'1010'
>>> '{0:o}'.format(10)     #八进制
'12'
>>> '{0:x}'.format(10)     #16进制
'a'
>>> '{:,}'.format(12369132698)  #千分位格式化
'12,369,132,698'

5、使用索引

>>> li
['hoho', 18]
>>> 'name is {0[0]} age is {0[1]}'.format(li)
'name is hoho age is 18

转载自http://www.cnblogs.com/plwang1990/p/3757549.html

原文地址:https://www.cnblogs.com/fanren224/p/8457279.html