找到字符串中符合的一段字符串 替换掉
要找到字符串中符合条件的一段字符串,并替换掉,可以使用字符串的replace()方法来实现。
例如,假设要找到字符串中符合条件的一段字符串"abc",并替换为"def",可以使用以下代码:
string = "Hello abc world!"
substring = "abc"
replacement = "def"
new_string = string.replace(substring, replacement)
print(new_string)
运行以上代码,输出结果为:
Hello def world!
在这个例子中,原始字符串是"Hello abc world!",要找到符合条件的一段字符串"abc",并将其替换为"def"。使用replace()方法将字符串中的"abc"替换为"def",得到新的字符串"Hello def world!"。最后将新的字符串打印出来。
注意,replace()方法会返回一个新的字符串,原始字符串不会被修改。如果要修改原始字符串,可以将新的字符串赋值给原始字符串变量,如string = string.replace(substring, replacement)
原文地址: https://www.cveoy.top/t/topic/iBEB 著作权归作者所有。请勿转载和采集!