对python 中re.sub,replace(),strip()的区别详解

1.strip():

str.strip([chars]);去除字符串前面和后面的所有设置的字符串,默认为空格

chars -- 移除字符串头尾指定的字符序列。

st = "  hello  "
st = st.strip()
print(st+"end")

输出:

对python 中re.sub,replace(),strip()的区别详解

如果设置了字符序列的话,那么它会删除,字符串前后出现的所有序列中有的字符。但不会清除空格。

st = "hello"
st = st.strip('h,o,e')
print(st)

因为,在h去除之后,e便出现在首位,所以e也会被去除,最终得到的答案就是ll

对python 中re.sub,replace(),strip()的区别详解

2.replace():

替代字符串中的某一些子串为另一些字符。 str.replace(old, new[, max])

old -- 将被替换的子字符串。

new -- 新字符串,用于替换old子字符串。

max -- 可选字符串, 替换不超过 max 次

替换某一个子串:

st = "i want a apple"
st = st.replace("apple","mice")
print(st)

规定最大替换次数:

st = "i want a apple and a apple"
st = st.replace("apple","mice",1)
print(st)

对python 中re.sub,replace(),strip()的区别详解

3.re.sub()

替换字符串中的某些子串,可以用正则表达式来匹配被选子串。

re.sub(pattern, repl, string, count=0, flags=0)

pattern:表示正则表达式中的模式字符串;

repl:被替换的字符串(既可以是字符串,也可以是函数);

string:要被处理的,要被替换的字符串;

count:匹配的次数, 默认是全部替换

如下,用正则方便多了,匹配所有连续出现的数字(把2019换成了danshenggou:):

st = "hello 2019"
st = re.sub("([0-9]+)","danshengou",st)
print(st)

对python 中re.sub,replace(),strip()的区别详解

匹配连续出现两次的a,并把它换成一个。

st = "hello aabbaa"
st = re.sub("(a{2})","a",st)
print(st)

对python 中re.sub,replace(),strip()的区别详解

以上这篇对python 中re.sub,replace(),strip()的区别详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。