字符串是不可变的
字符串格式化
基本的转换说明符:
- %字符:标记转换的开始
- 转换标志:-、+、0、空格等
- 最小字段宽度:转换后字符串的宽度。
- 精度:小数点的位数
- 转换类型:d 带符号的十进制整数;x 不带符号的十六进制; f 十进制浮点数;s 字符串。
>>> ##简单转换
>>> 'x:%d' % 42
'x:42'
>>> 'x:%x' % 42
'x:2a'
>>> 'x:%s' % 'y'
'x:y'
>>> ##字段宽度和精度
>>> '%10.2f' % pi
' 3.14'
>>> '%.2f' % pi
'3.14'
>>> ###符号、对齐和0填充
>>> '%010.2f' % pi
'0000003.14'
>>> '%-10.2f' % pi
'3.14 '
>>> '% 10.2f' % pi
' 3.14'
>>> '%+10.2f' % pi
' +3.14'
字符串方法
名称 | 含义 |
---|---|
find | 查找字符串并返回最左端索引 |
join | 在序列中元素间填充字符串 |
lower | 返回字符串小写字母版 |
replace | 返回替换后的字符串 |
split | 将字符串分割成序列 |
strip | 返回去除两端空格的字符串 |
translate | 进行多个替换 |
>>> title='Monty Python'
>>> title.find('Python')
6
>>> x=['1','2','3']##元素必须是字符串
>>> y='*'
>>> y.join(x)
'1*2*3'
>>> 'PYTHON'.lower()
'python'
>>> 'This is a test'.replace('a','two')
'This is two test'
>>> '1*2*3'.split('*')
['1', '2', '3']
>>> ' haha '.strip()
'haha'
>>> from string import maketrans
>>> table=maketrans('cs','kz')
>>> 'this is an incredible test'.translate(table,' ')
'thizizaninkredibletezt'
用时2.5h 今日效率有点低…