繁体   English   中英

用python循环中的不同子字符串替换字符串的相同子字符串出现

[英]Replacing same substring occurrences of a string with different substrings from looping in python

我是 python 的新手,我想使用 python 用不同的子字符串替换特定字符串的相同子字符串出现。 我已经尝试了 python 的 .replace() 函数,但它用新的子字符串替换了所有出现的地方。 问题示例如下。


字符串=“我是一个学生一个老师”在这里,我希望通过添加额外的字符的字符串替换子“”与“XAS”和“青年大使计划”。 最终的结果应该是“我是个学生XAS以及亚斯老师”


我尝试过的代码:

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`

您可以通过以下方式通知更换它应该更换多少次

s = "I am a student as well as a teacher"
s = s.replace("as","xxx",1)
print(s) #I am a student xxx well as a teacher
s = s.replace("as","yyy",1)
print(s) #I am a student xxx well yyy a teacher

编辑:第一替换asxas和第二asyas需要不同的方法

s = "I am a student as well as a teacher"
repl = ["xas","yas"]
s = s.split("as")
for i in repl:
    s = [i.join(s[:2])]+s[2:]
s = s[0]
print(s) #I am a student xas well yas a teacher

注意,该解决方案假定的元素的数目repl是exatcly等于数量的ass

您也可以使用正则表达式:

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

但是Daweo 使用 str.replace () 且限制为 1 的解决方案更优雅。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM