python - 用列表的元素替换所有出现的子字符串
问题描述
我在解决 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"
我已经尝试了很多不同的方法来到达我想去的地方,并用谷歌搜索了这个问题的解决方案,但没有遇到任何问题。我将非常感谢您的帮助!
解决方案
我有使用非常短的字符串 .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))
推荐阅读
- angular - 如何将材质嵌套树扩展到特定节点?
- c# - 如何通过C#获取Word中带有脚注的文本
- python - Keras 深度学习简介:“X_train”未定义?
- spring - Spring Integration 文件同步器:根据预定义的列表接受文件
- reactjs - 如何使用反应挂钩从 API 传递数据?
- java - 如何在 Appium 中使用 Xpath 获取最后一个元素
- php - Smarty While 嵌套循环仅显示第一行
- json - 如何将 Varbinary 列转换为 Base64 字符串以保存为 Json?
- mysql - 在 mysql 中显示数据库注释
- regex - PowerShell - 删除文本文件中分隔符之间的多行文本