Python format 格式化输出
格式化字符串的函数 str.format()
与 f-string
的格式几乎一致,因此我把它放在一起学习与记录。
Member and Element Access
format 函数可以接受不限个参数,位置可以不按顺序。
不设置指定位置序号, 则按默认顺序访问
1
2In [14]: "{}, {}".format("hello", "world")
Out[14]: 'hello, world'指定位置序号,则按照指定的顺序访问
对 format() 括号中的参数编号,然后前面字符串需要哪个位置的,便填写对应序号。
1
2In [16]: "{1}, {0}, {1}".format("value_0", "value_1")
Out[16]: 'value_1, value_0, value_1'通过名字访问
1
2
3
4
5
6In [17]: name = "Violetu"
In [18]: sex="male"
In [19]: "{sex}, {name}".format(name=name, sex=sex)
Out[19]: 'male, Violetu'通过索引访问
这里的
0[0]
是指第零个元素(person)的索引 0 位置。1
2
3
4In [20]: person = ["Violetu", "male"]
In [21]: "name: {0[0]}, sex: {0[1]}".format(person)
Out[21]: 'name: Violetu, sex: male'注: 这里的 0 不可以省略。
通过属性访问
1
2
3
4
5
6
7In [28]: class test:
...: def __init__(self, value):
...: self.value = value
...: my_value = test(6)
In [29]: "value is {0.value}".format(my_value)
Out[29]: 'value is 6'通过键值访问
1
2In [42]: "name: {name}, sex: {sex}".format(**person_dict)
Out[42]: 'name: Violetu, sex: male'
Numerical Representation
'{:x}'.format(100) |
Hexadecimal representationOutput:
64 |
---|---|
'{:X}'.format(3487) |
Hexadecimal representation (uppercase
letters) Output: D9F |
'{:#x}'.format(100) |
Hexadecimal representation (including the
0x ) Output: 0x64 |
'{:b}'.format(100) |
Binary representation Output: 1100100 |
'{:c}'.format(100) |
Character representation Output: d |
'{:d}'.format(100) |
Decimal representation (default)
Output: 100 |
'{:,}'.format(1000000) |
With thousands separator Output: 1,000,000 |
'{:o}'.format(100) |
Octal representation Output: 144 |
'{:n}'.format(100) |
Like d , but uses locale
information for separators Output: 100 |
'{:e}'.format(0.0000000001) |
Exponent notation Output: 1.000000e-10 |
'{:E}'.format(0.0000000001) |
Exponent notation (capital 'E')
Output: 1.000000E-10 |
'{:f}'.format(3/14.0) |
Fixed point Output: 0.214286 |
'{:g}'.format(3/14.0) |
General format Output: 0.214286 |
'{:%}'.format(0.66) |
Percentage Output: 66.000000% |
'{:.3}'.format(0.214286) |
Precision Output: 0.214 |
Field Width and Alignment
{number}:{padding}{align}{+}{width}{type}
整数 type=d
- padding character: 冒号后面,对齐符号前边写,只能是一个字符,不指定则默认是用空格填充。
- align symbol:
^
,<
,>
分别是居中、左对齐、右对齐, 默认是右对齐。 +
: 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格- width:宽度,只有宽度大于数字宽度事,对齐才有意义。
1 | In [66]: f"{3:5d}" |
字符串 type 为空
1 | In [83]: '{:*^15}'.format('text') |
小数 type=f
1 | In [86]: f"{3.14159:x>+10.2f}" |
解释:带符号,宽度为 10, 右对齐,填充 x
,
保留两位小数。
Conversions
'{!r}'.format('string') |
Calling repr on argumentsOutput:
'string' |
---|---|
'{!s}'.format(1.53438987) |
Calling str on arguments |