字符串操作

基本转换
指定要在字段中包含的值后,就可添加有关如何设置其格式的指令了。首先,可以提供一个
转换标志。
>>> print("{pi!s} {pi!r} {pi!a}".format(pi="π"))
π 'π' '\u03c0'
上述三个标志( s 、 r 和 a )指定分别使用 str 、 repr 和 ascii 进行转换。函数 str 通常创建外观
普通的字符串版本(这里没有对输入字符串做任何处理)。函数 repr 尝试创建给定值的Python表
示(这里是一个字符串字面量)。函数 ascii 创建只包含ASCII字符的表示,类似于Python 2中的
repr 。
你还可指定要转换的值是哪种类型,更准确地说,是要将其视为哪种类型。例如,你可能提
供一个整数,但将其作为小数进行处理。为此可在格式说明(即冒号后面)使用字符 f (表示定
点数)。
>>> "The number is {num}".format(num=42)
'The number is 42'
>>> "The number is {num:f}".format(num=42)
'The number is 42.000000'
你也可以将其作为二进制数进行处理。
>>> "The number is {num:b}".format(num=42)
'The number is 101010'
这样的类型说明符有多个,完整的清单见表


3.3.3 宽度、精度和千位分隔符
设置浮点数(或其他更具体的小数类型)的格式时,默认在小数点后面显示6位小数,并根
据需要设置字段的宽度,而不进行任何形式的填充。当然,这种默认设置可能不是你想要的,在
这种情况下,可根据需要在格式说明中指定宽度和精度。
宽度是使用整数指定的,如下所示:
>>> "{num:10}".format(num=3)
' 3'
>>> "{name:10}".format(name="Bob")
'Bob '
如你所见,数和字符串的对齐方式不同。对齐将在下一节介绍。
精度也是使用整数指定的,但需要在它前面加上一个表示小数点的句点。
>>> "Pi day is {pi:.2f}".format(pi=pi)
'Pi day is 3.14'
这里显式地指定了类型 f ,因为默认的精度处理方式稍有不同(相关的规则请参阅“Python
库参考手册”)。当然,可同时指定宽度和精度。
>>> "{pi:10.2f}".format(pi=pi)
' 3.14'
实际上,对于其他类型也可指定精度,但是这样做的情形不太常见。
>>> "{:.5}".format("Guido van Rossum")
'Guido'
最后,可使用逗号来指出你要添加千位分隔符。
>>> 'One googol is {:,}'.format(10**100)
'One googol is 10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,00
0,000,000,000,000,000,000,000,000,000,000,000,000,000,000'
3.3.4 符号、对齐和用 0 填充
有很多用于设置数字格式的机制,比如便于打印整齐的表格。在大多数情况下,只需指定宽
度和精度,但包含负数后,原本漂亮的输出可能不再漂亮。另外,正如你已看到的,字符串和数
的默认对齐方式不同。在一栏中同时包含字符串和数时,你可能想修改默认对齐方式。在指定宽
度和精度的数前面,可添加一个标志。这个标志可以是零、加号、减号或空格,其中零表示使用
0来填充数字。
>>> '{:010.2f}'.format(pi)
'0000003.14'
要指定左对齐、右对齐和居中,可分别使用 < 、 > 和 ^ 。
>>> print('{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}'.format(pi))
3.14
3.14
3.14
可以使用填充字符来扩充对齐说明符,这样将使用指定的字符而不是默认的空格来填充。
>>> "{:$^15}".format(" WIN BIG ")
'$$$ WIN BIG $$$'
还有更具体的说明符 = ,它指定将填充字符放在符号和数字之间。
>>> print('{0:10.2f}\n{1:10.2f}'.format(pi, -pi))
3.14
-3.14
>>> print('{0:10.2f}\n{1:=10.2f}'.format(pi, -pi))
3.14
- 3.14
字符串方法

例如让字符串str居中,总长度是39,两边填充空格

例如让字符串str居中,两边填充*




你还可指定搜索的起点和终点(它们都是可选的)。


字符合并一个字符串列表:










就是对应的把用k替换c,用z替换s
