1.使用%格式化字符串
Python中使用%格式化字符串的格式是 format % values
>>> 'I am %s' % 'python'
'I am python'
如果values是多个值,那么需要使用表示tuple的圆括号括起来:
>>> 'This is %s, that is %s' % ('python', 'java')
'This is python, that is java'
values也可以是字典,如果是字典那么format里需要用映射键的方法取值:
>>> 'I am %(lang)s' % {'lang':'python'}
'I am python'
以上示例中的%s里的s表示转换类型为str,Python也支持很多其他类型,以下列出常见的几种
- d/i:有符号的十进制整数
>>> '1 + 1 = %d'% 2
'1 + 1 = 2'
>>> '1 + 1 = %i'% 2
'1 + 1 = 2'
- o:有符号的八进制整数
>>> 'decimal 9 convert to octal is %o' % 9
'decimal 9 convert to octal is 11'
- x/X:有符号十六进制数
>>> 'decimal 17 convert to hex is %x' % 17
'decimal 17 convert to hex is 11'
- f/F:浮点数十进制格式
>>> '%f' % 3.14
'3.140000'
- e/E:浮点数指数格式
>>> '%e' % 31.4
'3.140000e+01'
- c:单个字符
>>> '%c' % 97
'a'
>>> '%c' % 'a'
'a'
- r:字符串(使用repr()转换任何Python对象)
>>> 'hello %r' % 'world'
"hello 'world'"
- s:字符串(使用str()转换任何Python对象)
>>> 'hello %s' % 'world'
'hello world'
- a:字符串(使用ascii()转换任何Python对象)
>>> 'hello %a' % 'world'
"hello 'world'"
如果需要原样表示%,只需要%%即可
>>> '3 %% 2 = %d' % 1
'3 % 2 = 1'
可以指定占位宽度,如果实际内容小于宽度,默认右对齐,左边补空格
>>> '%3s' % 'a'
' a'
>>> '%3d' % 10
' 10'
对于浮点数,可以使用.precision的格式指定精度
>>> '%.3f' % 3.1415
'3.142'
>>> '%.3f' % 3.14
'3.140'
可以使用转换标志对转换行为进行一些控制,支持的转换标志如下:
- ‘#’:替代模式
# 八进制和十进制转换在替代模式下会显示 0o个0x/0X前缀
>>> '%o' % 9
'11'
>>> '%#o' % 9
'0o11'
>>> '%#x' % 17
'0x11'
>>> '%#X' % 17
'0X11'
# 浮点数转换在替代模式下会始终保留一个小数在末尾,即使精度为0的整数
>>> '%.0f' % 3.0
'3'
>>> '%#.0f' % 3.0
'3.'
- ‘0’:数值类型转换时多余位置补0
>>> '%03d' % 1
'001'
- ‘-’:转换值靠左对齐(会覆盖’0’转换)
>>> '%-3d' % 1
'1 '
- ‘’:(空格)正数前边保留一个空格
>>> '% d' % 1
' 1'
>>> '% d' % -1
'-1'
以上这些符号使用时遵守以下规则和顺序:
%[M][F][W][P][L]T
%:固定格式
M:映射键(可选),由加圆括号的字符序列组成,values是字典的情况下使用
F:转换标志(可选),用于影响某些转换类型的结果
W:最小字段宽度(可选),如果指定为'*',则实际宽度从values元组的下一元素中读取,要转换的对象则为最小字段宽度和可选的精度
P:精度(可选),以在'.'之后加精度值的形式给出。如果指定为'*',则实际精度会从values元组的下一元素中读取
L:长度修饰符(可选)
T:转换类型
注:长度修饰符(h、l或L)可以使用,但是会被忽略,因为在Python3中只有长整型(L),没有短整型(h),所有%ld和%d是一样的。
小面是一些组合使用的示例:
# 十进制浮点数转换类型(f),带符号位(+),最小宽度5(5),精度1位(.1)
>>> '%+-5.1f' % 3.14
'+3.1 '
# 十进制整数转换类型(d),带符号位(+),最小宽度4(4),不足位补0(0)
>>> '%+04d' % 16
'+016'
# 字符串转换类型(s),左对齐(-),最小宽度6(6),精度2(.2)
>>> '%-6.2s' % 'Python'
'Py '
2.使用str.format格式化字符串
从python3开始官方推荐使用字符串自带的format方法对字符串进行格式化,该方法能够完全兼容%的形式且更强大,比如像下面这样:
>>> 'hello {}!'.format('world')
'hello world!'
format的语法定义如下:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
arg_name ::= [identifier | integer]
attribute_name ::= identifier
element_index ::= integer | index_string
index_string ::= <any source character except "]"> +
conversion ::= "r" | "s" | "a"
format_spec ::= <described in the next section>
下面通过举例的方法逐一对format语法定义中的字段进行解释
- field_name/arg_name : 参数名(可选),可以是位置(integer)或者名称(identifier)
# arg_name为空,则按照顺序依次引用后面的位置参数
>>> '{} {} {}'.format('first','second','third')
'first second third'
# arg_name为位置(integer),则按照索引号引用后面的位置参数
>>> '{0} {1} {2}'.format('first','second','third')
'first second third'
>>> '{2} {1} {0}'.format('first','second','third')
'third second first'
>>> '{0} {0} {1}'.format('first','second','third')
'first first second'
# 但是空和位置引用不能混用
>>> '{} {1} {2}'.format('first','second','third')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot switch from automatic field numbering to manual field specification
# arg_name为名称(identifier),则按照名称引用后面的关键字参数
>>> '{f1} {f2} {f3}'.format(f1='first', f2='second', f3='third')
'first second third'
# 空引用和名称引用混用,或者数字引用和名称引用混用是可以的
>>> '{} {f2} {}'.format('first', 'third', f2='second')
'first second third'
>>> '{0} {f2} {1}'.format('first', 'third', f2='second')
'first second third'
- field_name/arg_name.attribute_name : 属性名(可选),是对参数的属性进行引用
>>> c = 3-5j
>>> 'realpart = {0.real}, imagpart = {0.imag}'.format(c)
'realpart = 3.0, imagpart = -5.0'
>>> 'realpart = {cnum.real}, imagpart = {cnum.imag}'.format(cnum=c)
'realpart = 3.0, imagpart = -5.0'
- field_name/arg_name[element_index] : 元素索引(可选),可以是数字或名称,通过索引的方式引用参数的元素
# 数字索引
>>> arr = [1,2]
>>> 'e1 = {0[0]}, e2 = {0[1]}'.format(arr)
'e1 = 1, e2 = 2'
# 名称索引
>>> d = {'id':1, 'name': 'tom'}
>>> 'id = {0[id]}, name = {0[name]}'.format(d)
'id = 1, name = tom'
format_spec的语法定义如下:
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
fill ::= <any character>
aligb ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= integer
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
下面通过举例的方式逐一对format_spec语法定义中的字段进行解释
- width : 最小宽度
# 指定最小宽度为10位
>>> '{:10}'.format('Python')
'Python '
- align : 对齐方式,支持’<‘、’>‘、’^'三种方式
>>> '{:<30}'.format('left aligned') # 最小宽度30,并且左对齐
'left aligned '
>>> '{:>30}'.format('right aligned') # 最小宽度30,并且右对齐
' right aligned'
>>> '{:^30}'.format('center') # 最小宽度30,并且居中对齐
' center '
- fill : 填充符
# 最小宽度30,并且居中对齐,多余部分使用*填充
>>> '{:*^30}'.format('centered')
'***********centered***********'
- sign : 符号位,仅对数学类型有效,支持’+‘、’-‘、’ '三种类型
>>> '{:+}, {:+}'.format(1, -1) # 始终保留符号位
'+1, -1'
>>> '{:-}, {:-}'.format(1, -1) # 负数才有符号位
'1, -1'
>>> '{: }, {: }'.format(1, -1) # 正数前保留一个空格
' 1, -1'
- precision : 精度
>>> '{:.2}'.format(3.14)
'3.1'
>>> '{:.2}'.format('Python') # 作用在字符串上则会进行截断
'Py'
- , : 千分位
>>> '{:,}'.format(12345678)
'12,345,678'
- type : 转换类型
转换类型大部分与%格式化的方式相同,下面只对不一样的类型进行示例说明
>>> '{:b}'.format(7) # 二进制类型
'111'
>>> '{:.2%}'.format(23/89) # 百分比类型
'25.84%'
- #/0 : # 和0的作用与%格式化的方式相同