用不同的子字符串替换出现在同一字符串中的子字符串,以免在python中循环

时间:2019-01-20 10:23:04

标签: python python-3.x

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


string =“我是学生,,还是是老师” 在这里,我想通过向子字符串添加额外的字符,将子字符串“ as ”替换为“ xas ”和“ yas ”。最终结果应为“我是学生 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`

2 个答案:

答案 0 :(得分: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

编辑:用as替换第一个xas,用as替换第二个yas需要不同的方法

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的元素数完全等于ass的元素数。

答案 1 :(得分:0)

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

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

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