我想知道如何在 Python 3.4 中使用列表来格式化多个相同的关键字。我的设置方式是,用户可以传入一个字符串,该字符串包含多个关键字,程序将在这些关键字的位置生成名称,结果应该是一个句子,其中的关键字替换为名称。
我已经创建了一种方法,可以根据程序在用户传入的字符串中看到的数量来生成名称,但由于字符串的性质,无法立即替换它们。由于该字符串有多个相同的关键字(例如 {name}),我需要能够用一个唯一的字符串替换它们中的每一个。这在 Python 3.4 中可能吗?
用户传入的字符串可以是
"{name} had a wonderful day at the park, but then {name} came and ruined it"
在程序生成名称后,它应该是
"John had a wonderful day at the park, but then Bob came and ruined it"
干杯。
编辑:要补充一点,我没有发现任何关于使用列表或具有多个关键字但唯一替换的内容,所以如果我必须用另一种方式而不是替换也可以。
最佳答案
您可以使用 string.replace
使用可选的 count
参数并将其限制为每次仅替换一个名称:
>>> names = ['John', 'Bob']
>>> message = "{name} had a wonderful day at the park, but then {name} came and ruined it"
>>> i = 0;
>>> while '{name}' in message:
... message = message.replace('{name}', names[i], 1)
... i += 1
...
>>> message
'John had a wonderful day at the park, but then Bob came and ruined it'
关于 python 3 : Formatting a string with multiple same keywords but unique strings to replace them,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33202200/