python中的格式化字符串

python中的格式化字符串概述:https://docs.python.org/zh-cn/3/tutorial/inputoutput.html#

格式化字符串共有三种方式:

①旧的printf风格,从C语言来的  https://docs.python.org/zh-cn/3/library/stdtypes.html#printf-style-bytes-formatting

②str.format()方式:https://docs.python.org/zh-cn/3/tutorial/inputoutput.html#the-string-format-method

③f-string:https://docs.python.org/zh-cn/3/reference/lexical_analysis.html#formatted-string-literals

这三种方式中,f-string是python新特性,也是我认为三者中最好用的一种。

而②和③的使用语法基本上是一样的,官网中解释的非常详细:

格式化字符串语法:https://docs.python.org/zh-cn/3/library/string.html#format-string-syntax

格式规格:https://docs.python.org/zh-cn/3/library/string.html#format-specification-mini-language

 

我在这里再总结一下

str.format()的使用形式:'{a的格式描述} {b的格式描述}'.format(a,b)   每组大括号与后面的一个变量对应

f-string的使用形式:f'{a:a的格式描述} {b:b的格式描述}'   需要为字符串添加前缀f来告诉解释器这是一个f-string

(a/b既可以是变量,也可以是字面值)

其中格式描述如下:

'{:填充符 对齐符 正负号 # 0 字符串总宽度 千位分隔符 .精度 类型}'

    填充符:当不满足给定宽度时用该字符填充

    对齐符:<左对齐  ^居中  >右对齐  =将填充符放在正负号后数字前

    正负号:+显示正数的正号

    #:在非十进制数前面添加0b/0o/0x前缀

    0:为数字智能填充0

    字符串总宽度:一个正整数

    千位分隔符:逗号',' 或 下划线'_'

    精度:一个正整数

    类型:十进制d、二进制b、八进制o、十六进制x/X、普通浮点数f、指数浮点数e/E、百分比格式%、字符c、字符串s

 

下表举例对比了三种方式:

 

printf风格

str.format()

f-string

输出

显示正号,宽度为7,保留2位小数

'%+07.2f' % (3.1415)

'{:+07.2f}'.format(3.1415)

f'{3.1415:+07.2f}'

'+003.14'

左对齐,宽度为5

'%-5d' % (42)

'{:<5d}'.format(42)

f'{42:<5d}'

'42   '

居中,宽度为5,不够填星号

 

'{:*^5d}'.format(42)

f'{42:*^5d}'

'*42**'

右对齐,宽度为5,不够填0

'%05d' % (42)

'{:0>5d}'.format(42)

f'{42:0>5d}'

'00042'

二进制

 

'{:b}'.format(42)

'{:#b}'.format(42)

f'{42:b}'

f'{42:#b}'

'101010'

'0b101010'

八进制

'%o' % (42)

'%#o' % (42)

'{:o}'.format(42) 

'{:#o}'.format(42)

f'{42:o}'

f'{42:#o}'

'52'

'0o52'

十六进制

'%x' % (42)

'%#x' % (42)

'{:x}'.format(42)

'{:#x}'.format(42)

f'{42:x}'

f'{42:#x}'

'2a'

'0x2a'

多个字符串连接

(设name='peter', a=3)

'%s have %d books' % (name, a) '{} have {:d} books'.format(name, a) f'{name} have {a:d} books' 'peter have 3 books'

 

 

猜你喜欢

转载自blog.csdn.net/yuejisuo1948/article/details/104641583