首页 > 解决方案 > Python:如何用元组中的值替换多次出现的字符串

问题描述

我有一个字符串,例如: "Hello %s, how are %s, %s"

我需要%s用元组的元素替换所有出现的("world", "you", 1),以便输出为:

Hello world, how are you, 1

标签: python

解决方案


你可以这样做:

def tupleFormat(string, format):
    return string % format

然后你可以做你的例子:

tupleFormat("Hello %s, how are %s, %s", ("world", "you", 1))

您可以完全按照您想要的方式对字符串和元组使用 % 运算符。


推荐阅读