Newbie advice for string fromatting

Raymond Hettinger vze4rx4y at verizon.net
Wed Jul 2 12:49:53 EDT 2003


"gt" <gtewalt at earthlink.net> wrote in message
news:f9b7c11d.0307020642.7231cd82 at posting.google.com...
> O.k., four days into playing with python
> and I have a little problem that I would like
> to get some feedback on.
> ( as far as the best way to go about it )
>
> Basically, just a little Mad-Libs type script.
>
> Something like:
>
> libs = ["adverb", "noun", "verb", "tool"]
> words = {a:j, n:j, v:j, t:j}
> for x in libs:
>        print "Enter a ", x, ": ",
>        words[j] = raw_input()
> print "The %s %s %s with a %s." % (a, n, v, t)
>
> What is the most efficient way to do something like this?

You're on the right track.
Using dictionaries with the % formatting operator is efficient.

Subclassing a dictionary with a question asker is an
approach that keeps the code simple and separates it
from the actual madlib strings.

So, here is version to get you started:


>>> farmtale = """
At %(name)s farms, we drive a %(machine)s over
the %(vegetable)s crops and feed %(food)s to our
%(animal)s."""

>>> class Madlib(dict):
    def __getitem__(self, key):
        return raw_input("Enter a %s:  " % key)


>>> print farmtale % Madlib()
Enter a name:  Donald
Enter a machine:  clock
Enter a vegetable:  squash
Enter a food:  pizza
Enter a animal:  snake

At Donald farms, we drive a clock over
the squash crops and feed pizza to our
snake.


Raymond Hettinger






More information about the Python-list mailing list