[Tutor] string formatting

Wayne Werner waynejwerner at gmail.com
Mon Sep 19 19:47:01 CEST 2011


On Mon, Sep 19, 2011 at 10:46 AM, Pirritano, Matthew
<MPirritano at ochca.com>wrote:

> <snip>

You some variables say:
>
> X = "sky"
> Y = "blue"
>
> Print "the %(x)s is %(y)s" % locals()
>
> the sky is blue
>
> That works! And in cases where I'm replacing over 20 strings it's much
> easier than having to include a tuple at the end. Especially when
> there's only two or three variables I'm replacing repeatedly, in which
> case a dictionary seems like overkill.
>

I suspect your email program auto-capitalized the initial X and Y, and P for
you, as that code would actually create a syntax and KeyError (or two).

Technically speaking, locals() is already dictionary:

>>> type(locals())
<class 'dict'>

and just for the sake of completeness, in newer (2.6(?) or greater) versions
of Python, you can use the format() method:

x = 'sky'
y = 'blue'

print('The {x} is {y}.'.format(locals()))

HTH,
-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110919/d5d91ca9/attachment.html>


More information about the Tutor mailing list