Newbie advice for string fromatting

Sean Ross frobozz_electric at hotmail.com
Wed Jul 2 11:21:14 EDT 2003


I don't know whether this is efficient, but its an example of your code in a
form that actually works:

words = {"adverb":None, "noun":None, "verb":None, "tool":None}
keyorder = ["adverb", "noun", "verb", "tool"]   # modify dictionary in this
order
for word in keyorder:
       print "\nEnter a(n)", word, ": ",
       words[word] = raw_input()
print "\nThe %(adverb)s %(noun)s %(verb)s with a %(tool)s." % words


"gt" <gtewalt at earthlink.net> wrote in message
> libs = ["adverb", "noun", "verb", "tool"]
> words = {a:j, n:j, v:j, t:j}

For the code above to work as-is, all of a, n, v, t, and j would have to be
variables (which is not the case). In my version, I've used your libs words
as keys to the dictionary, and I've given each dictionary item a value of
None to start with. Also, since dictionaries do not maintain items in the
order that they are added, and because you appear to want to ask for words
in a particular order, I've used the list 'keyorder'. If order was
unimportant, you could get rid of keyorder altogether and just use:

...
for word in words:
    ...
...

But then you get things like "Enter a(n) tool: ", "Enter a(n) noun: ",
etc...

[snip]
> print "The %s %s %s with a %s." % (a, n, v, t)

Instead of using the "string" % tuple, you can also use "string with
keywords" % dict,
which allows you to re-use your 'words' dictionary (no need to create
variables a, n, v, t).

HTH
Sean






More information about the Python-list mailing list