【问题标题】:Python: How can I replace multiple occurrences of a string with values in tuplePython:如何用元组中的值替换多次出现的字符串
【发布时间】:2020-12-25 17:35:09
【问题描述】:

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

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

Hello world, how are you, 1

【问题讨论】:

标签: python


【解决方案1】:

如果您的目标是替换出现的字符串,您可以尝试以下方法:

string = 'Hello %s, how are %s, %s'
tupl = ('world', 'you', '1')

for t in tupl:
  string = string.replace('%s', t, 1)

print(string)

输出:

Hello world, how are you, 1

【讨论】:

    【解决方案2】:

    您可以使用.format() 方法:

    print("Hello {0}, how are {1}, {2}".format(*("world", "you", 1)))
    

    星号* 允许您解包元组,以便.format() 函数可以详细说明它们。

    查看here 了解更多示例。

    如果你不想使用.format(),看看这个:

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

    两种方法都会输出:

    Hello world, how are you, 1
    

    【讨论】:

      【解决方案3】:

      有一个简单的答案:

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

      输出:

      Hello world, how are you, 1
      

      【讨论】:

        【解决方案4】:

        你可以这样做:

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

        然后你可以做你的例子:

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

        您可以完全按照自己的意愿对字符串和元组使用 % 运算符。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-11-24
          • 1970-01-01
          • 2013-04-24
          • 2021-08-14
          • 2011-06-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多