replace()
描述
replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
语法
replace()方法语法:
str.replace(old, new[, max])
参数
old – 将被替换的子字符串。
new – 新字符串,用于替换old子字符串。
max – 可选字符串, 替换不超过 max 次
返回值
返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。
str = "th ht sth th!!!"
print(str.replace("h", "www"))
#结果:twww wwwt stwww twww!!!
str = "th ht sth th!!!"
print(str.replace("th", "66", 3))
#结果:66 ht s66 66!!!
strip()
描述
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)或字符序列。
注意
:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
语法
strip()方法语法:
str.strip([chars]);
参数
chars – 移除字符串头尾指定的字符序列。
返回值
返回移除字符串头尾指定的字符序列生成的新字符串。
a = "hello python olleh"
b = a.strip("h")
print(b)
#结果:ello python olle
c = a.strip("h,e,l,o") #移除字符串前后的h后,e就在前后,直到遇到第一个不包含在其中的字符为止。
print(c)
#结果: python
re.sub()
描述
替换字符串中的某些子串,可以用正则表达式来匹配被选子串。
语法
re.sub(pattern, repl, string, count=0, flags=0)
参数
pattern:表示正则表达式中的模式字符串;
repl:被替换的字符串(既可以是字符串,也可以是函数);
string:要被处理的,要被替换的字符串;
count:匹配的次数, 默认是全部替换
返回值
返回替换后新的字符串。
import re
s = "hello 2020 2020 2020 2020"
s1 = re.sub("([0-9]+)", "python", s, 3)
print(s1)
#结果:hello python python python 2020