如果您使用大括号而不是方括号,那么您的字符串可以用作字符串格式化模板。您可以使用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(']','}')