In Python, I’m trying to add elements from an array into a string using “%s”.
However, at compile time, the size of the array, and the string i’m interpolating into, are unknown. The idea is that i’m making a madlibs type script which pulls the text from a separate file.
Current code:
from sys import argv
script, input = argv
infile = open(input)
madlibs = eval(infile.readline())
words = []
for word in madlibs:
words.append(raw_input("Give me a %s: " % word))
print infile.read() % words
So, the first line of the input file contains the madlib questions, and the subsequent text has the story. Here is the example input file i’m using:
["noun", "verb", "verb", "noun"]
There once was a %s named Bill.
He liked to %s all the time.
But he did it too much, and his girlfriend got mad.
She then decided to %s him to get back at him.
He died. It's a sad story.
They buried him. And on his tombstone, they placed a %s.
So, in an ideal world,
print infile.read() % words
would work, as it would just interpolate the elements in “words” into the string pulled from the file.
However, it doesn’t, and i’m out of ideas. Any help?
Make sure
wordsis a tuple:By the way, a MadLib sometimes repeats the same supplied word. It would therefore be easier to make
wordsadictinstead oflist. You could then do something like this:which yields