常用方法举例
使用%设置字符串格式,适用场景相对单一
>>> "%s, %s!" % ('Hello','world',)
'Hello, world!'
>>>
使用f开头的格式化(python3上支持,python2不支持)
Python 3.6.8 (default, May 26 2019, 10:58:36)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> name = "Foodly"
>>> print(f"hello {name}")
hello Foodly
>>> print(f"the {name} has {len(name)} char")
the Foodly has 6 char
>>>
[root@CSDN ~]#python2
Python 2.7.5 (default, Oct 11 2015, 17:47:16)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> name = "Foodly"
>>> print(f"hello {name}")
File "<stdin>", line 1
print(f"hello {name}")
^
SyntaxError: invalid syntax
>>>
使用format方法设置字符串格式,应用场景更广
>>> "{},{} and {}".format(1,2,3)
'1,2 and 3'
>>> "{2},{0} and {1}".format(2,3,1)
'1,2 and 3'
>>> from math import pi
>>> "pi={value:.2f}".format(value=pi)
'pi=3.14'
>>> #当变量名称一致时可以简写
>>> f"{pi:.2f}"
'3.14'
>>>
要在最终结果中包含花括号则需要两对花括号
>>> '{{:{}}}'.format(4)
'{:4}'
>>> '{{:{}}}'.format(4).format('xl')
'xl '
>>>
像上面的‘%s’和{pi:.2f}里面的s和f是类型说明符
类型 | 含义 |
---|---|
b | 将整数表示为二进制数 |
c | 将整数解读为Unicode码点 |
d | 将整数视为十进制数处理(整数默认使用的说明符) |
e | 科学计数法表示小数(用e来表示指数) |
E | 与e相同,E表示指数 |
f | 将小数表示为定点数 |
F | 与f相同,特殊值用大写表示 |
g | 自动在定点表示和科学表示法之间做出选择,这是默认的小数说明符,但在默认的情况下至少有1位小数 |
G | 与g相同,但使用大写表示特殊值 |
n | 与g相同,但插入随区域而异的数字分隔符 |
o | 将整数表示为八进制 |
s | 字符串默认说明符 |
x | 将整数表示为十六进制 |
X | 与x相同,使用大写字母 |
% | 将数表示为百分百值 |
宽度、精度和千分位分隔符
>>> "{num:5}".format(num=3)
' 3'
>>> "{name:5}".format(name='xl')
'xl '
>>> f"{pi:.3f}"
'3.142'
>>> "one billion is {:,}".format(10*10000*10000)
'one billion is 1,000,000,000'
>>>
符号、对其和0填充
>>> '{:05.2f}'.format(pi)
'03.14'
>>> print('{0:<12.2f}\n{0:^12.2f}\n{0:>12.2f}'.format(pi))
3.14
3.14
3.14
>>> '{:#^15}'.format('bb')
'######bb#######'
>>> '{:a^15}'.format('bb')
'aaaaaabbaaaaaaa'
>>> '{:#15.2f}'.format(pi)
' 3.14'
>>> '{:#^15.2f}'.format(pi)
'#####3.14######'
>>>
>>>> '{:.2f}'.format(+pi)
'3.14'
>>> '{:.2f}'.format(-pi)
'-3.14'
>>> '{:+.2f}'.format(-pi)
'-3.14'
>>> '{:+.2f}'.format(+pi)
'+3.14'
>>> '{:+.2f}'.format(pi)
'+3.14'
>>>