[英]Python 3: Formatting a string with multiple same keywords but unique strings to replace them
我想知道如何使用列表來格式化Python 3.4中的多個相同關鍵字。 我設置它的方式是用戶可以傳入一個字符串,該字符串具有多個關鍵字,用於程序將在其位置生成的名稱,結果應該是一個句子,其中關鍵字被替換為名稱。
我已經創建了一個方法來根據程序在用戶傳入的字符串中看到的數量生成名稱,但由於字符串的性質,不能立即替換它們。 由於字符串具有多個相同的關鍵字(例如{name}),因此我需要能夠用唯一的字符串替換它們中的每一個。 這可能在Python 3.4中有用嗎?
用戶傳入的字符串可以是
"{name} had a wonderful day at the park, but then {name} came and ruined it"
並且在程序生成名稱后應該是
"John had a wonderful day at the park, but then Bob came and ruined it"
干杯。
編輯:要添加,我沒有找到任何關於使用列表或具有多個關鍵字但唯一替換的東西,所以如果我必須采取另一種方式而不是替換它也可以。
您可以將string.replace
與可選的count
參數一起使用,並將其限制為每次只替換一個名稱:
>>> names = ['John', 'Bob']
>>> message = "{name} had a wonderful day at the park, but then {name} came and ruined it"
>>> i = 0;
>>> while '{name}' in message:
... message = message.replace('{name}', names[i], 1)
... i += 1
...
>>> message
'John had a wonderful day at the park, but then Bob came and ruined it'
您可以使用count
參數:
>>> s = "{name} had a wonderful day at the park, but then {name} came and ruined it"
>>> s = s.replace('{name}', 'John', count=1)
>>> s
'John had a wonderful day at the park, but then {name} came and ruined it'
>>> s = s.replace('{name}', 'Bob', count=1)
>>> s
'John had a wonderful day at the park, but then Bob came and ruined it'
如果您已根據每次替換的次數預先生成了一個項目列表,則可以使用re.sub
以編程方式從列表中選擇下一個項目。 這將比str.replace
具有更好的性能,尤其是。 如果你有一個大字典的關鍵字和一個大文本。
例如:
import re
# Function to look up an item and return the next thing in its list.
def replace(m):
return D[m.group(1)].pop(0)
D = {'name' : ['John','Bob'], 'place' : ['park']}
text = "{name} had a wonderful day at the {place}, but then {name} came and ruined it"
new_text = re.sub('{(.*?)}',replace,text)
print(new_text)
輸出:
John had a wonderful day at the park, but then Bob came and ruined it
但是,似乎您需要為不同的名稱使用不同的變量。 然后你可以使用字典format
:
進口重新
D = {'name1':'John', 'name2':'Bob', 'place':'park'}
text = "{name1} had a wonderful day at the {place}, but then {name2} came and ruined it. {name2} is a jerk!"
print(text.format(**D))
輸出:
John had a wonderful day at the park, but then Bob came and ruined it. Bob is a jerk!
如果我理解你的話,這應該有效:
first_name = Bob
second_name = Sam
"%s had a wonderful day at the park, but then %s came and ruined it" % (first_name, second_name)
可能是最干凈的方法
如果短語總是在示例中間隔良好,您可以這樣做
s = "{name} had a wonderful day at the park, but then {name} came and ruined it"
names = ['John', 'Bob']
ni = iter(names)
outs = ' '.join(next(ni) if el=='{name}' else el for el in s.split())
print(outs)
哪個產生
'John had a wonderful day at the park, but then Bob came and ruined it'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.