format 用法
本文根据官方文档及自己理解整理,只整理出自己可以理解的部分,h因个人水平有限,难免有所错误和纰漏,欢迎批评指正。
格式{ [field_name] ["!" conversion] [":" format_spec] }
"{" [field_name] ["!" conversion] [":" format_spec] "}"
大括号的内容大概分为两部分,冒号":"前的部分和后面的部分。里面的参数全部都可以省略。
冒号前部分主要为数据引用和转化部分
冒号后面为指定详细的显示格式(format specification)
冒号前部分
冒号前的部分,分两块,一块为field_name,另一块为使用叹号"!"开头conversion(指定函数转化)
field_name
field_name可以有以下几种方式:
常规:
1.指定索引
2.省略,什么也不写,默认为其在字符串中的位置索引,从0开始。
3.标识符
复杂:
- 指定索引或标识符的前提下,使用其attribute_name(属性名) 比如point.x;0.name等方式
- 指定索引或标识符的前提下,使用其element_index(索引),比如lst[2];0[0]等
>>> "Hello,My name is {},I'm {}.".format('Wesley','12')
"Hello,My name is Wesley,I'm 12."
>>> "Hello,My name is {0},I'm {1}.".format('Wesley','12')
"Hello,My name is Wesley,I'm 12."
>>> "Hello,My name is {name},I'm {age}.".format(age='12',name='Wesley')
"Hello,My name is Wesley,I'm 12."
比较复杂一些
>>> "Hello,My name is {0[0]},I'm {0[1]}.".format(youth)
"Hello,My name is Wesley,I'm 12."
>>> "Hello,My name is {boy[0]},I'm {boy[1]}.".format(boy=youth)
"Hello,My name is Wesley,I'm 12."
>>> from collections import namedtuple
>>> Person=namedtuple("Persion",['name','age'])
>>> boy = Person('Wesley',12)
>>> "Hello,My name is {0.name},I'm {0.age}.".format(boy)
"Hello,My name is Wesley,I'm 12."
>>> "Hello,My name is {boy.name},I'm {boy.age}.".format(boy=boy)
"Hello,My name is Wesley,I'm 12.
conversion部分
conversion部分:
- !s 调用函数str()
- !r 调用函数repr()
- !a 调用函数ascii()
对传进来的数值使用format函数之前,首先使用指定的函数对其进行强制类型转换为str类型。str(),repr()和ascii()三个函数转换为字符串的方式有所不同。若省略,则由__format__函数自动处理。
冒号后部分
format_spec语法
format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= digit+
grouping_option ::= "_" | ","
precision ::= digit+
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
format_spec对于不同类型的数值,其支持的参数不同。
字符串
format specification中,很多方法只支持数字,相对来说,对数值做字符串处理,主要支持以下:
- 宽度,width : 用数字标识
- 对齐 align: 对字符串分别用'<' '^' '>' 标识 左对齐 居中 右对齐
- 填充 fill : 用指定字符填充空白位,默认为空格
对齐填充和宽度
字符串,默认左对齐,默认填充为空格;
都可以省略,可以指定对齐方式,填充省略,默认为空格。
若要修改填充,必须指定对齐方式
对齐分三种,左对齐('<'),右对齐('>'),居中('^')
>>> '{:}'.format("hello")
'hello'
指定宽度为10个字符,默认为左对齐
>>> '{:10}'.format("hello")
'hello '
指定宽度为10个字符,右对齐
>>> '{:>10}'.format("hello")
' hello'
指定宽度为10个字符,居中对齐,空白字符用“*”填充
>>> '{:*^10}'.format("hello")
'**hello***'
若填充为0,还可以在宽度前加一个数字0,字符串格式同样遵循指定对齐方式
指定宽度为10个字符,居中对齐,空白字符用“0”填充。
>>> '{:^010}'.format("hello")
'00hello000'
字符串各种不怎么用前导0做填充,这个主要给数字格式用的,其默认的对齐方式为‘=’,只能在数字格式中使用的对齐方式)
>>> '{:010}'.format("hello")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: '=' alignment not allowed in string format specifier
数字类型
format specification中,对于数字类型,同样有宽度,填充和对齐方式选项,相对于字符串,数字类型还支持:
- sing 控制符 ’+‘ ’-‘ ’和space
- 进制转换
- 小数位控制
- 前导0
- 第四种对齐方式‘=’
sing位
数字专用,sign 位置在对齐align后面,#、前导0或宽度前面;
sign | 正数3.14 | 负数3.14 |
---|---|---|
“+” | 不显示符号“3.14” | 显示负号(-)“-3.14” |
“-” | 显示正号(+)“+3.14” | 显示负号(-)“-3.14” |
空格 | 前面有个空格“ 3.14” | 显示负号(-)“-3.14” |
进制转换和井号
花括号内最右边的字段type,用来指这个数据如何被显示出来。对整数来说,可以指定type很多,如下表:
Type | Meaning |
---|---|
'b' | Binary format. Outputs the number in base 2. 二进制 |
'c' | Character. Converts the integer to the corresponding unicode character before printing.字符 |
'd' | Decimal Integer. Outputs the number in base 10. 默认,十进制 |
'o' | Octal format. Outputs the number in base 8.八进制 |
'x' | Hex format. Outputs the number in base 16, using lower- case letters for the digits above 9.小写16进制 |
'X' | Hex format. Outputs the number in base 16, using upper- case letters for the digits above 9.大写16进制 |
'n' | Number. This is the same as 'd' , except that it uses the current locale setting to insert the appropriate number separator characters. |
None | The same as 'd' . |
>>> '{:}'.format(97)
'97'
>>> '{:d}'.format(97)
'97'
>>> '{:n}'.format(97)
'97'
>>> '{:b}'.format(97)
'1100001'
>>> '{:o}'.format(97)
'141'
>>> '{:x}'.format(97)
'61'
>>> '{:c}'.format(97)
'a'
>>> '{:x}'.format(0x61)
'61'
井号#用来显示数字的前缀
>>> '{:#b}'.format(97)
'0b1100001'
>>> '{:#x}'.format(97)
'0x61'
来个组合的,显示97的二进制形式,显示正负号,指定宽度为20,居中对齐,填充@
>>> '{:@^+#20b}'.format(97)
'@@@@@+0b1100001@@@@@'
小数点精度
对于小数位,type位有很多,我就能看懂f e 和 %,只用过f和%,别的还没用过。
type 'f', 将数字表示为小数部分,默认为6位小数点;超位舍弃,"四舍六入五取偶"的方式舍弃
>>> '{:f}'.format(122)
'122.000000'
>>> '{:f}'.format(122.0000006)
'122.000001'
使用.precision用来确定小数点精度;其位置在倒数第二位[type]前面
>>> '{:.2f}'.format(122.0000006)
'122.00'
居中对齐,宽度20,两位小数点位置,填充为-
>>> '{:-^20.2f}'.format(122)
'-------122.00-------'
前导0和align ‘=’
对字符串指定宽度,默认alignment 为 ‘<’ 左对齐;
对数字,指定快递,默认alignmeng为‘>‘ 右对齐;
>>> '{:10}'.format('-12') #字符串
'-12 '
>>> '{:10}'.format(-12) #数字
' -12'
空白字符默认为空格;可以使用前导0对空白字符进行填充;
>>> '{:010}'.format(-12)
'-000000012'
使用前导0后,其对齐方式看似右对齐('>'),其实是使用了对齐方式‘=’,'='与'>'的区别在与符号位的位置
'=',符号位置在首位;即在填充位的前面
‘>’,符号位跟数字在一起
>>> '{:010}'.format(-12)
'-000000012'
>>> '{:>010}'.format(-12)
'0000000-12'
>>> '{:0=10}'.format(-12)
'-000000012'
>>> '{:0>10}'.format(-12)
'0000000-12'
format的嵌套
>>> '{:{}{}}'.format(3,.2,"f")
'3.00'
以下为官方文档的案例
>>> for align, text in zip('<^>', ['left', 'center', 'right']):
... '{0:{fill}{align}16}'.format(text, fill=align, align=align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'
>>>
>>> octets = [192, 168, 0, 1]
>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
'C0A80001'
>>> int(_, 16)
3232235521
>>>
>>> width = 5
>>> for num in range(5,12):
... for base in 'dXob':
... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
... print()
...
5 5 5 101
6 6 6 110
7 7 7 111
8 8 10 1000
9 9 11 1001
10 A 12 1010
11 B 13 1011