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