python-格式化字符串
https://www.cnblogs.com/longyuu/p/14695553.html
python格式化字符串有三种方式:
1、百分号形式(%) :默认右对齐 。 "-"表示左对齐
常用的类型码: s -->字符串 d---->数字 f--->浮点数
1)字符 %s
2)整数 %d
3)小数 %f %[+-宽度.精度]f
# 【精度】,就是小数点后保留的位数,默认是6位
# 【宽度】,字符串的长度
【小数】
In [176]: n
Out[176]: 23.256
In [177]: "%10.2f"%3.1415926
Out[177]: ' 3.14'
In [178]: "%10.3f"%3.1415926
Out[178]: ' 3.142'
In [179]: "%10.0f"%3.1415926
Out[179]: ' 3'
2、字符串的format方法形式---先进一点
字符默认左对齐,数字默认有对齐。【{冒号+填充字符+对齐方式+字符宽度+类型码}】-->【{:x>10}】
^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
+ 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格
b、d、o、x 分别是二进制、十进制、八进制、十六进制。
此外我们可以使用大括号 {} 来转义大括号。
对整数或者浮点数可以不加d、f,可以自动识别
十进制整数:d
浮点数:f
十六进制数:X、x
In [162]: "{:10}".format("zzdsad")
Out[162]: 'zzdsad '
In [163]: "{:10}".format(100)
Out[163]: ' 100'
In [193]: print ("{} 对应的位置是 {{0}}".format("hello"))
hello 对应的位置是 {0}
In [194]: n=3.1415926
In [195]: "{:>12}".format(n)
Out[195]: ' 3.1415926'
In [196]: "{:<12}".format(n)
Out[196]: '3.1415926 '
In [197]: "{:x<12}".format(n)
Out[197]: '3.1415926xxx'
【1】按位置方位参数
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 参数的索引可以重复
'abracadabra'
【2】按名称访问参数
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
【3】按序列的索引位置访问
>>> coord = (3,5)
>>> "X:{0[0]};Y:{0[1]}".format(coord)
'X:3;Y:5'
>>> coord = [6,7]
>>> "X:{0[0]};Y:{0[1]}".format(coord)
'X:6;Y:7'
>>> coord = "12"
>>> "X:{0[0]};Y:{0[1]}".format(coord)
'X:1;Y:2'
>>>
【3】文本对齐、指定宽度、填充字符
>>> '{:<30}'.format('left aligned')
'left aligned '
>>> '{:>30}'.format('right aligned')
' right aligned'
>>> '{:^30}'.format('centered')
' centered '
>>> '{:*^30}'.format('centered') # use '*' as a fill char
'***********centered***********'
【4】使用逗号作为千位分隔符:
>>> '{:,}'.format(1234567890)
'1,234,567,890'
【5】百分数
>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'
【6】特定格式的格式化---日期时间
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'
【7】替代 %x
和 %o
以及转换基于不同进位制的值:
#自带进制转换
>>> # format also supports binary numbers
>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
'int: 42; hex: 2a; oct: 52; bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
【8】替代%s和%r
#注意两个的区别
>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"
>>> "repr() shows quotes: {}; str() doesn't: {}".format('test1', 'test2')
"repr() shows quotes: test1; str() doesn't: test2"
【9】替代 %+f
, %-f
和 % f
以及指定正负号:
>>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'
【10】嵌套参数以及更复杂的示例:
>>> for align, text in zip('<^>', ['left', 'center', 'right']):
... '{0:{fill}{align}16}'.format(text, fill=align, align=align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'
>>> 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
2.1字符串的format_map方法
format_map(mapping)
mapping为字典类型的参数
In [102]: d
Out[102]: {'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
In [103]: "Cecil's phone number is {Cecil}.".format_map(d) #{Cecil},必须要是字典的键
Out[103]: "Cecil's phone number is 3258."
3、f-string
f-string 是 python3.6 之后版本添加的,称之为字面量格式化字符串,是新的格式化字符串的语法。
f-string 格式化字符串以 f 开头,后面跟着字符串,字符串中的表达式用大括号 {} 包起来,它会将变量或表达式计算后的值替换进去。
字符默认左对齐,数字默认有对齐。
使用方式类似format方法:f"{变量+冒号+填充字符+对齐方式+宽度+类型码}"-->f"{name:x>20s}"
若有多个变量或表达式,则每个变量或表达式用花括号括起来。https://www.cnblogs.com/longyuu/p/12738408.html
>>> s = "qwew"
>>> f"{s:10}"
'qwew '
>>> n
3.145
>>> d=200
>>> f"{d:10}"
' 200'
>>> name = "liming"
>>> f"{name:@>10s}"
'@@@@liming'
>>> f"{name:@>20s}"
'@@@@@@@@@@@@@@liming'
>>> f"{name:@>20d}"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'str'
In [87]: name = "三少爷"
In [88]: f"你好! {name}"
Out[88]: '你好! 三少爷'
In [89]: f"{1+2}"
Out[89]: '3'
>>> n = 3.145 >>> f"{n:}" '3.145' >>> f"{n:10}" ' 3.145' >>> f"{n:<10}" '3.145 ' >>> f"{n:^10}" ' 3.145 ' >>> f"{n:x^10}" 'xx3.145xxx' >>> f"{n:x^10.2}" 'xxx3.1xxxx' >>> f"{n:x^10.0f}" 'xxxx3xxxxx' >>> f"{n:x^10.1f}" 'xxx3.1xxxx' >>> f"{n:x^10.2f}" 'xxx3.15xxx' >>>
在 Python 3.8 的版本中可以使用 = 符号来拼接运算表达式与结果:
>>> x = 1 >>> print(f'{x+1}') # Python 3.6 2 >>> x = 1 >>> print(f'{x+1=}') # Python 3.8 'x+1=2'
下面举例说明:
输入三行字符,1)以指定宽度左右对齐;
2)以最长字符串的长度左右对齐
str1 = input("请输入第一行文字:")
str2 = input("请输入第二行文字:")
str3 = input("请输入第三行文字:")
1、%形式---默认右对齐
以指定宽度对齐:20宽度
右对齐:
print("%20s" % str1) print("%20s" % str2) print("%20s" % str3)
左对齐:
print("%-20s" % str1) print("%-20s" % str2) print("%-20s" % str3)
以最长字符串宽度对齐:
右对齐:
max_length = max(len(str1),len(str2),len(str3)) # fmt = "%%%ds" % max_length #“%数字s” fmt = "%" + str(max_length) + "s" print(fmt) print(fmt % str1) print(fmt % str2) print(fmt % str3)
左对齐:
max_length = max(len(s1),len(s2),len(s3))
# fmt = "%%%ds" % -max_length #“%数字s”
fmt = "%" + str(-max_length) + "s"
print(fmt)
print(fmt % str1)
print(fmt % str2)
print(fmt % str3)
2、format形式
指定宽度:
右对齐:
print("{:>20}".format(str1))
print("{:>20}".format(str2))
print("{:>20}".format(str3))
左对齐:
print("{:<20}".format(str1))
print("{:<20}".format(str2))
print("{:<20}".format(str3))
最长字符宽度:
右对齐:#自定义宽度,用变量max_length绑定,传入里面的 "{}"
print("{:>{}}".format(str1,max_length))
print("{:>{}}".format(str2,max_length))
print("{:>{}}".format(str3,max_length))
左对齐:#自定义宽度,用变量max_length绑定,传入里面的 "{}"
print("{:<{}}".format(str1,max_length))
print("{:<{}}".format(str2,max_length))
print("{:<{}}".format(str3,max_length))