我是 python 的新手,我想使用 python 将特定字符串的相同子字符串替换为不同的子字符串。我已经尝试过 python 的 .replace() 函数,但它用新的子字符串替换了所有出现的地方。该问题的示例如下。
string = "我是一名学生也是一名老师" 在这里,我想通过向子字符串添加额外的字符来将子字符串“as”替换为“xas”和“yas”。最后的结果应该是“I am a student xas well yas a teacher”
我试过的代码:
string = "I am a student as well as a teacher"
occurrences = re.findall("as", string)
substr = ["xas","yas"]
i = 0
for occur in occurrences:
string = string.replace(occur, substr[i])
i = i + 1`
请您参考如下方法:
您也可以使用正则表达式:
substr = ["xxx","yyy"]
def replace_with(_):
"""Returns first value of substr and removes it."""
return substr.pop(0)
import re
string = "I am a student as well as a teacher"
print(re.sub("as",replace_with,string))
输出:
I am a student xxx well yyy a teacher
但是使用 str.replace() 的解决方案限制为 1 by Daweo更优雅。
