str.replace(old, new[, max])
old — 将被替换的子字符串。
new — 新字符串,用于替换old子字符串。
max — 可选字符串, 替换不超过 max 次
#示例代码
In [3]: str
Out[3]: ‘this is python string example,this is python string example’
In [2]: print(str.replace(“is”,“IS”,3))
thIS IS python string example,thIS is python string example
设置只提换3个,所以第四个is就没有被替换成大写
re.sub(pattern, repl, string, count=0, flags=0)
pattern:表示正则表达式中的模式字符串;
repl:被替换的字符串(既可以是字符串,也可以是函数);
string:要被处理的,要被替换的字符串;
count:匹配的次数, 默认是全部替换
flags:具体用处不详
示例代码
In [5]: re.sub(r’is|ing’,‘ING’,str)
Out[5]: ‘thING ING python strING example,thING ING python strING example’
.strip()
对于这个函数要记住3点:
- 默认删除行首或者行尾的空白符(包括’\n’, ‘\r’, ‘\t’, ’ ')
- 能使用,分隔去除多个值
3.lstrip()表示删除左边的,rstrip()表示删除右边的
In [16]: s= ’ afaf’
In [17]: s.strip()
Out[17]: ‘afaf’