python 3 : Formatting a string with multiple same keywords but unique strings to replace them

标签 python string python-3.x replace keyword

我想知道如何在 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/

相关文章:

python - urlopen/requests.get 在导入模块中创建的线程中不起作用

python - PyCharm 和 IronPython 代码完成?

python - 查找连接到图中每个节点的最小节点数的简单方法

mysql - 如何在MySQL中获取特定字符之后和特定字符之前的字符串?

python - PyQt 4 : setupUi() unbound method error

java - java中将字符串转换为变量

python - 在 python 中使用字符串模块和 ascii 打印单词?

Python:为什么我的模块变量丢失了它们的内容?

python - python3 中的可选 yield 或 return。如何?

python - 如何在遍历列表时删除项目?