這是一個簡單的問題。我有一個通用字串,我想*用提供的引數替換星號。
'* is the capital of *'
如果我給出兩個論點('Berlin','Germany'),我應該得到
'Berlin is the capital of Germany'
這是一個簡單的問題,我可以解決它,但我正在尋找一個行解決方案,其中每個位置引數都替換相應的*. 我想,我見過這種型別的東西(*) ...(*),但不記得了。有人有什么想法嗎?
uj5u.com熱心網友回復:
你有很多方法可以做到這一點,如果你有 2 個元素的元組,一個簡單的方法:
t = ('Berlin', 'Germany')
'{} is the capital of {}'.format(*t)
要么
'%s is the capital of %s' % t
輸出:'Berlin is the capital of Germany'
uj5u.com熱心網友回復:
您可以像這樣使用 f-String:
city = "Berlin"
country = "Germany"
print(f"{city} is the capital of {country}")
基本上,您不再使用引數和格式,而是將 python 代碼直接放入字串中。
uj5u.com熱心網友回復:
如果將 '*' 替換為 '{}',則可以使用以下format方法:
s = '* is the capital of *'
replacement = ['Berlin', 'Germany']
print(s.replace('*', '{}').format(*replacement))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442607.html
上一篇:為什么str.replace使用單個例外值會慢得多?
下一篇:我想將編碼的字串作為輸出。但不能
