簡體   English   中英

Python:如何用元組中的值替換多次出現的字符串

[英]Python: How can I replace multiple occurrences of a string with values in tuple

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

我需要用元組的元素("world", "you", 1)替換所有出現的%s ,以便輸出:

Hello world, how are you, 1

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

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

星號*允許您解包元組,以便.format()函數可以詳細說明它們。

在這里查看更多示例。

如果你不想使用.format() ,看看這個:

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

兩種方法都會輸出:

Hello world, how are you, 1

你可以這樣做:

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

然后你可以做你的例子,如:

tupleFormat("Hello %s, how are %s, %s", ("world", "you", 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

有一個簡單的答案:

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

輸出:

Hello world, how are you, 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM