[Tutor] string formatting

Sivan Orkin sivanorkin at gmail.com
Sun Sep 18 02:06:26 CEST 2011


On Sun, Sep 18, 2011 at 01:51, Matthew Pirritano <
matthewpirritano at sbcglobal.net> wrote:

> All,****
>
> ** **
>
> I know that I can do this:****
>
> ** **
>
> "the %s is %s" % ('sky', 'blue')****
>
> ** **
>
> But I have very large blocks of text and I thought there was another way
> like****
>
> ** **
>
> X = “sky”****
>
> Y = “blue”****
>
> ** **
>
> "the %(X)s is %(Y)s"****
>
> ** **
>
> But I’ve tried this and it is not working. I’m just trying to get it to
> work in the interpreter right now.****
>
> ** **
>
> I’m using python 2.6.5. I need to use this version because it is compatible
> with the software that it is working with (SPSS).****
>
> ** **
>
> What am I missing?****
>
> ** **
>
> Thanks****
>
> Matt
>

Hello Matt,

Your problem lies in that Python doesn't know with what to replace the
%(name)s.
If you use plain %s (with no name in parentheses), Python will use the order
of the tuple you give as argument to % to replace the %s in the string.
However, if you want to use argument names (like %(x)s), Python needs to
know what to replace these with.

A hint: % either takes a tuple () as argument, or a dictionary {}.
A dictionary has key-value pairs; what would be the key, and what the value?

Hope that helps!

Sivan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110918/b15d3bd8/attachment.html>


More information about the Tutor mailing list