[英]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
你可以這樣做:
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.