python - 使用列表替换字符串中的子字符串

标签 python python-3.x

我正在寻找一种更符合 Python 风格的方法,用列表中的值替换字符串中已知长度的占位符。它们应该按顺序更换并且只能使用一次。例如,值:

replaceVals = ['foo', 'bar']

origStr = 'I went to the ? to get ?'

我希望获得:

newStr = 'I went to the foo to get bar'

我能够通过以下循环获得所需的结果,但我觉得应该有比使用这样的循环更好的方法来解决这个问题。

for i in range(len(replaceVals)):
   origStr = origStr.replace('?', replaceVals[i], 1)

最佳答案

您可以使用字符串的replaceformat 方法,如下所示:

origStr.replace('?','{}').format(*replaceVals)

Out[334]: 'I went to the foo to get bar'

关于python - 使用列表替换字符串中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54487514/

相关文章:

python - 计算pandas面板数据集中并发实体的数量

python - 保持卡住集中元素的顺序

python - ImportError:libSM.so.6:无法打开共享对象文件:没有这样的文件或目录

python 转置除第一列之外的列表列表

python - 无法打开数据库文件 - Mayan EDMS

python - Pandas 没有在 y 轴上显示 timedelta 所需的结果

python-3.x - 在词形还原中应用多个 pos 参数

python-3.x - PIL 的 ImageDraw 中可用的确切颜色名称是什么?

python - 使用 read_json 函数将 json 行规范中的 json 转换为 panda?

python - 删除大 CSV 文件的第一行?