Loop Inside .Format()

Keywords: python-3.x


I'm creating a small madlibs game.

I have a class that holds the interpolated string. I get input form users which I put into a list of words I'll use with interpolated string.

Now, I can do the following:


But any given madlib might have a large number of parameters for the string, it seems like there should be some way to loop through my list and have it fill in the string parameters, but I'm hitting a wall with this process.


You can use the "splat"/"unpacking" operator:

print(STRING.format(*madLibInserts)) # * "expands" the list out as arguments to format

Note though, if there are more placeholders that words in madLibsInserts, you will get an index error, and if there's less, the remaining placeholders will be ignored.