3.1 字符串基本操作
所有的标准序列操作(索引、切片、乘法、成员资格检查、长度、最小值和最大值)都适用于字符串,但别忘了字符串是不可变的,因此所有的元素赋值和切片赋值都是非法的
3.2 设置字符串的格式:精简版
3.3 设置字符串的格式:完整版
3.3.1 替换字段名
>>> "{foo} {} {bar} {}".format(1, 2, bar=4, foo=3)
>>>> '3 2 4 1'
>>> "{foo} {1} {bar} {0}".format(1, 2, bar=4, foo=3)
>>> '3 2 4 1'
3.3.2 基本转换
>>> print("{pi!s} {pi!r} {pi!a}".format("pi"))
>>> pi 'pi' '\u03c0'
>>> "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'
类型 | 含义 |
---|---|
b | 将整数表示为二进制数 |
c | 将整数解读为Unicode码点 |
d | 将整数视为十进制数进行处理,这是整数默认使用的说明符 |
e | 使用科学表示法来表示小数 |
f | 将小数表示为定点数 |
o | 将整数表示为八进制数 |
x | 将整数表示为十六进制数并使用小写字母 |
X | 将整数表示为十六进制数但使用大写字母 |
% | 将数表示为百分比值 |
3.3.3 宽度、精度和千位分隔符
>>> "{num:10}".format(num=3)
>>> 3
>>> "Pi day is {pi:.2f}".format(pi=pi)
>>> 'Pi day is 3.14'
>>> ''One googol is {:,}".format(10**100)
>>> 'One googol is 10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,.....'
3.3.4 符号、对齐和用0填充
>>> "{:010.2f}".format(pi)
>>> '0000003.14'
>>> '{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 $$$'
3.4 字符串方法
3.4.1 center
方法center通过在两边添加填充字符(默认是空格)让字符串居中
>>> 'Beijing'.center(39)
>>> Beijing
>>> 'Beijing'.center(39,'*')
>>> *******Beijing*******
3.4.2 find
方法find在字符串中查找子串。如果找到,就返回子串中第一个字符的索引,否则返回-1
3.4.3 join
其作用与split相反,用于合并序列的元素
>>> seq = ['1', '2', '3', '4', '5']
>>> sep = '+'
>>> sep.join(seq)
>>> '1+2+3+4+5'
3.4.4 lower
3.4.5 replace
>>> 'This is a test'.replace('is', 'ez')
>>> 'This ez a test'
3.4.6 split
>>> '1+2+3+4+5'.split('+')
>>> ['1', '2', '3', '4', '5']
3.4.7 strip
方法strip将字符串两边的空白删除