所有标准的序列操作(索引、分片、乘法、判断成员资格、求长度、取最小值和最大值)对字符串同样适用。但是字符串是不可改变的。
字符串格式化使用字符串格式化操作符(%)来实现。
>>> "Hello,%s" % ‘world‘ ‘Hello,world‘
元组或字典实现:
>>> print("Hello,%s. %s enough for ya?" % (‘world‘,‘Hot‘)) Hello,world. Hot enough for ya?
转换类型 | 含义 |
---|---|
d,i | 带符号的十进制数 |
o | 不带符号的八进制数 |
u | 不带符号的十进制数 |
x | 不带符号的十六进制数(小写) |
X | 不带符号的十六进制数(大写) |
e | 科学计数法表示的浮点数(小写) |
E | 科学计数法表示的浮点数(大写 ) |
f,F | 十进制浮点数 |
g | 如果指数大于-4或者小于精度值则和e相同,其他情况与F相同 |
G | 如果指数大于-4或者小于精度值则和E相同,其他情况与F相同 |
C | 单字符(接受整数或单字符串) |
r | 字符串(使用repr转换任意python对象) |
s | 字符串(使用str转换任意python对象) |
简单转换
只需写出转换类型:
>>> ‘Price of eggs:%d‘ % 42 ‘Price of eggs:42‘ >>> ‘Hexadecimal price of eggs:%x‘ % 42 ‘Hexadecimal price of eggs:2a‘
字段宽度和精度
>>> ‘%10f‘ % 3.1415926 ‘ 3.141593‘ >>> ‘%10.2f‘ % 3.1415926 ‘ 3.14‘ >>> ‘%.2f‘ % 3.1415926 ‘3.14‘ >>> ‘%.5s‘ % ‘dhfuhduioshduio‘ ‘dhfuh‘
可以使用*做为字段宽度或精度,此时数值会从元组参数中读取
>>> ‘%.*s‘ % (5,‘dhfuhduioshduio‘) ‘dhfuh‘ >>> ‘%*.*s‘ % (10,5,‘dhfuhduioshduio‘) ‘ dhfuh‘
符号、对齐和用0填充
在字段宽度和精度值之前还可以放一个标志,该标志可以是零(0),加号(+),减号(-)或空格
零(0)表示转换的值为数字时,不足宽度的部位将用0填充,转换的值为字符串时无影响
>>> ‘%010.2f‘ % 3.1415926 ‘0000003.14‘ >>> ‘%010.5s‘ % ‘udshkdsfhdkjf‘ ‘ udshk‘
减号(-)表示左对齐数值
>>> ‘%-10.2f‘ % 3.1415926 ‘3.14 ‘
加号(+)表示不管是正数还是负数都表示出正负号
>>> ‘%+5d‘ % 10 ‘ +10‘ >>> ‘%+5d‘ % -10 ‘ -10‘
空格表示在正数前加上空格
>>> ‘% 5d‘ % 10 ‘ 10‘ >>> ‘% 5d‘ % -10 ‘ -10‘
用于在一个长字符串中查找子串。返回子串所在位置的最左端索引。如果没有找到则返回-1
>>> title = "Monty Python‘s Flying Circus" >>> title.find(‘Monty‘) 0 >>> title.find(‘Python‘) 6 >>> title.find(‘Flying‘) 15 >>> title.find(‘Zirquss‘) -1
这个方法还可以接受可选的起始点和结束点参数,指定查找的字符串范围:
>>> subject = ‘$$$ Get rich now!!! $$$‘ >>> subject.find(‘$$$‘) 0 >>> subject.find(‘$$$‘,1) # 指定查找的起始点 20 >>> subject.find(‘!!!‘) 16 >>> subject.find(‘!!!‘,0,16) # 指定查找的起始点和结束点 -1
用于连接序列中的元素,被连接的元素都必须是字符串
>>> dirs = ‘‘,‘usr‘,‘bin‘,‘env‘ >>> ‘/‘.join(dirs) ‘/usr/bin/env‘ >>> seq = [‘1‘,‘2‘,‘3‘,‘4‘,‘5‘] >>> ‘+‘.join(seq) ‘1+2+3+4+5‘ >>> seq = [1,2,3,4,5] >>> ‘+‘.join(seq) Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> ‘+‘.join(seq) TypeError: sequence item 0: expected str instance, int found
用户返回字符串的小写字母
>>> ‘HELLO WORLD!‘.lower() ‘hello world!‘
用于替换字符串中的字符
>>> ‘This is a test‘.replace(‘is‘,‘eez‘) ‘Theez eez a test‘
用于将字符串分割成序列
>>> ‘1+2+3+4+5‘.split(‘+‘) [‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘] >>> ‘/usr/bin/env‘.split(‘/‘) [‘‘, ‘usr‘, ‘bin‘, ‘env‘]
用于去除字符串两侧(不包括内部)空格的字符串
>>> ‘ hello world! ‘.strip() ‘hello world!‘
原文:https://www.cnblogs.com/eastonliu/p/9094565.html