replace()
语法:
- str.replace ( old, new, max )
参数:
- old – 将被替换的子字符串。
- new – 新字符串,用于替换old子字符串
- max – 可选字符串, 替换不超过 max 次
例子:
a='i am a pig'
b=a.replace('am','was')
print(a)
print(b)
输出结果:`
i am a pig
i was a pig
re.sub()
语法:
- re.sub(pattern, repl, string, count=0, flags=0)
参数:
-
pattern:表示正则表达式中的模式字符串;
-
repl:被替换的字符串(既可以是字符串,也可以是函数);
-
string:要被处理的,要被替换的字符串;
-
count:匹配的次数, 默认是全部替换
-
flags:具体用处不详
例子:
import re
a='i am a pig or dog'
b=re.sub(r'pig|dog','human',a,count=1)
c=re.sub(r'pig|dog','human',a,count=2)
print(a)
print(b)
print(c)
输出结果:
i am a pig or dog
i am a human or dog
i am a human or human
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。