我正在寻找一种更符合 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)
最佳答案
您可以使用字符串的replace
和format
方法,如下所示:
origStr.replace('?','{}').format(*replaceVals)
Out[334]: 'I went to the foo to get bar'
关于python - 使用列表替换字符串中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54487514/