如果您使用大括號而不是括號,那麼您的字符串可以用作string formatting template。你可以使用itertools.product大量換人與填充:
import itertools as IT
text = "{person} is feeling really {how} today, so he's not going {where}."
persons = ['Buster', 'Arthur']
hows = ['hungry', 'sleepy']
wheres = ['camping', 'biking']
for person, how, where in IT.product(persons, hows, wheres):
print(text.format(person=person, how=how, where=where))
產生
Buster is feeling really hungry today, so he's not going camping.
Buster is feeling really hungry today, so he's not going biking.
Buster is feeling really sleepy today, so he's not going camping.
Buster is feeling really sleepy today, so he's not going biking.
Arthur is feeling really hungry today, so he's not going camping.
Arthur is feeling really hungry today, so he's not going biking.
Arthur is feeling really sleepy today, so he's not going camping.
Arthur is feeling really sleepy today, so he's not going biking.
生成隨機的句子,你可以使用random.choice:
for i in range(5):
person = random.choice(persons)
how = random.choice(hows)
where = random.choice(wheres)
print(text.format(person=person, how=how, where=where))
如果必須使用括號和在您的格式沒有大括號,你 可以取代用大括號括號,然後執行上述操作:
text = "[person] is feeling really [how] today, so he's not going [where]."
text = text.replace('[','{').replace(']','}')
可能是一個愚蠢的建議,但你看着字符串格式化'{}單曲? – akaIDIOT