转到下一行

2024-10-02 10:25:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,例如:

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."

有什么想法吗


Tags: 字符串列表stringismythisonesentence
2条回答

使用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

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

输出:

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

相关问题 更多 >

    热门问题