如果您使用大括号而不是括号,那么您的字符串可以用作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