3、使用字符串

字符串和元组类似是不可变的。

字符串的格式化:操作符为%

>>> test="hello,%s and %s!"
>>> values=('hou','kai')
>>> test % values
'hello,hou and kai!'
>>> from math import pi
>>> '%10f' % pi
' 3.141593'
>>> '%-10f' % pi
'3.141593 '
>>> '%010f' % pi
'003.141593'

如果使用列表或其他序列代替元组,那么序列会被解释为一个值。只有元组和字典可以格式化为一个以上的值。

转化标志-

左对齐

转化标志+

数值前加正负号

空白字符

正数之前保留空格,对齐正负数

0

位数不够用零补齐

最小字段宽度

最少占位数,如果是*,表示宽度从值元组获得

.后的精度

实数:小数点后位数;字符串,最大字段宽度;*元组读取

类似的还有string模块中的模板字符串

>>> from string import Template
>>> s=Template('$y,hou$x')
>>> s.substitute(x='kai',y='hello')
'hello,houkai'

字符串的方法:

find(rfind,index,rindex,count,startwith,endwith)

查找子字符串,返回最左端的索引,没找到返回-1

join

将字符按指定符号连接
>>> dirs=['1','2']
>>> '+'.join(dirs)
'1+2'

slpit

>>> '1+2'.split('+')
['1', '2']
默认间隔是所有空格(空格、制表、换行等)

lower(islower,capitalize,swapcase,title ,upper)

转化为小写

replace

替代指定部分

strip(lstrip,rstrip)

去除两侧空格,也可指定去除两侧的其他字符

translate

同replace,功能更灵活

原文地址:https://www.cnblogs.com/houkai/p/3478709.html