Newbie advice for string fromatting

gt gtewalt at earthlink.net
Wed Jul 2 18:14:36 EDT 2003


"Raymond Hettinger" <vze4rx4y at verizon.net> wrote in message news:<R2EMa.9$_O4.4 at nwrdny02.gnilink.net>...
> "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


Thanks Raymond, and Sean.
I posted at work this morning, so I didnt have Python
available to see if my idea actually worked or not.
It's good to know I wasn't totally off base though.
And, I'm making an educated guess, but I suppose
one could type up fairly large tales, let a user choose a 
category of a sort, and just import the tale modules.
Thanks again. :-)




More information about the Python-list mailing list