转到下一行并替换

时间:2016-12-11 09:45:26

标签: python python-3.x

我有一个字符串,例如:

String = "This is first sentence, sentence one. This is second sentence, sentence two`."

我想将“句子”替换为列表中的另一个词

my_list = ['1', 'me1', '2', 'me2']

所以它会变成:

"This is first 1, me1 one. This is second 2, me2 two."

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

使用regex.sub(repl, string, count=0)函数和自定义replace_substring函数作为替换回调的解决方案:

def replace_substring(m):
    if replace_substring.counter == len(my_list):
        replace_substring.counter = 0

    replaced = my_list[replace_substring.counter]
    replace_substring.counter += 1
    return replaced

replace_substring.counter = 0

String = "This is first sentence, sentence one. This is second sentence, sentence two`."
my_list = ['1', 'me1', '2', 'me2']
pattern = re.compile(r'\bsentence\b')

result = pattern.sub(replace_substring, String)
print(result)

输出:

This is first 1, me1 one. This is second 2, me2 two`.

https://docs.python.org/3/library/re.html#re.regex.sub

答案 1 :(得分:0)

String = "This is first sentence, sentence one. This is second sentence, sentence two`."
String1 = String
my_list = ['1', 'me1', '2', 'me2']

for i in range(len(my_list)):
    String1=String1.replace("sentence",my_list[i],1)
    print i, my_list[i]
print String1

Out put:

'This is first 1, me1 one. This is second 2, me2 two`.'