首页 > 解决方案 > 用列表的元素替换所有出现的子字符串

问题描述

我在解决 python 的一个小问题时遇到了麻烦:

我有一个包含子字符串的字符串,其数量等于其他字符串列表中元素的数量。我想用列表的元素替换这些子字符串。我的代码现在看起来的一个最小示例是:

import fileinput
#this string is in the text file "file_containing_string1"
string1 = "text substring text substring text substring text" 
list1 = [element1, element2, element3]

...

with fileinput.FileInput(file_containing_string1, inplace = True, backup = ".bak") as file:

    for element in list1:

        for line in file:
            print(line.replace("substring", element), end = "")

我想要获得的输出是:

"text element1 text element2 text element3 text"

我的代码产生的输出:

"text element1 text element1 text element1 text"

我已经尝试了很多不同的方法来到达我想去的地方,并用谷歌搜索了这个问题的解决方案,但没有遇到任何问题。我将非常感谢您的帮助!

标签: python

解决方案


我有使用非常短的字符串 .format 方法的解决方案:

string1 = "text substring text substring text substring text" #this string is in the text file "file_containing_string1"
list1 = ['element1', 'element2', 'element3']
string2=string1.replace('substring','{}')

print(string2.format(*list1))

推荐阅读