格式化

1.format-位置格式化

>>> '{0},{1},{2}'.format(1,2,3)
	      
'1,2,3'

  当参数个数小于(Max(位置索引)+1)时,系统报错

>>> '{0},{1},{3}'.format(1,2,3)
	      
Traceback (most recent call last):
  File "<pyshell#44>", line 1, in <module>
    '{0},{1},{3}'.format(1,2,3)
IndexError: tuple index out of range

  当参数个数>=(Max(位置索引)+1)时,即使位置索引不连续且不按升序排列,也可以格式化

>>> '{0},{3},{2}'.format(1,2,3,4)
	      
'1,4,3'
>>> 

  有时需要将{}也要打印出来,但是下面这种情况并没有发生替换

>>> '{{0}}'.format(1)
	      
'{0}'
>>> 

  使用转义

>>> '{{{0}}}'.format(1)
	      
'{1}'
>>> 

  对实际值更精确的格式化

>>> '{0:.2f}{1}'.format(22.3655, 'GB')
			 
'22.37GB'
>>> 

  

2.format-关键字格式化

>>> '{a},{b},{c}'.format(a=1,b=2,c=3)
	      
'1,2,3'
>>> 

3.关键字和位置格式化结合使用

  原则:位置格式化必须在关键字站位符前面使用

 

>>> '{a}{b}{0}'.format(a=1,b=2,3)
			 
SyntaxError: positional argument follows keyword argument
>>> '{0}{a}{b}'.format(3,a=1,b=2)
			 
'312'
>>> 

  

3.使用格式符格式化字符串

  格式化字符串时,我们要创建一个字符串模板,模板中使用格式符给真实值预留位置,并说明真实数值应该呈现的格式。Python需要给多个格式符传递值时,需要使用元组(tuple)

>>> '%s' % 'itxds'
	      
'itxds'
>>> '%s %s %s' % ('itxds', 'study', 'python')
	      
'itxds study python'
>>> 

如果要对格式进行更细的控制,可如下操作

%[(name)][flags][width].[precision]typecode

(name)为命名

flags可以有+,-,' '或0。+表示右对齐。-表示左对齐。' '为一个空格,表示在正数的左侧填充一个空格,从而与负数对齐。0表示使用0填充。

width表示显示宽度

precision表示小数点后精度

>>> '%+''10s' % 'itxds'
	      
'     itxds'

  

2.格式符列表

%s    字符串 (采用str()的显示)

>>> '%s' % 'itxds'
			 
'itxds'
>>> 

  

%r    字符串 (采用repr()的显示)

%c   字符串及ASCII码

>>> '%c' % 97
			 
'a'
>>> '%c' % 'afdfs'
			 
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    '%c' % 'afdfs'
TypeError: %c requires int or char
>>> '%c' % 'a'
			 
'a'
>>> 

  

>>> '%c %c %c' % (97,98, 'a')
			 
'a b a'
>>> 

  

%b    二进制整数

%d    十进制整数

>>> '%d + %d = %d' % (4,5,4+5)
			 
'4 + 5 = 9'
>>> 

  

%i    十进制整数

>>> '%i' % 1010
			 
'1010'

  

%o    八进制整数

>>> '%o' % 23
			 
'27'
>>> 

  

%x    十六进制整数

>>> '%x' % 10
			 
'a'
>>> 

  

%e    指数 (基底写为e)

>>> '%e' % 2.04565445
			 
'2.045654e+00'
>>>

  

%E    指数 (基底写为E)

%f    浮点数

%F    浮点数,与上相同

%g    指数(e)或浮点数 (根据显示长度)

%G    指数(E)或浮点数 (根据显示长度)

原文地址:https://www.cnblogs.com/xiangdongsheng/p/13415077.html