[Tutor] string formatting

Pirritano, Matthew MPirritano at ochca.com
Mon Sep 19 17:46:27 CEST 2011


Pythonistas,

This is the resolution of a question I asked over the weekend.

The method I was thinking of was in a program I wrote on my work
computer but couldn't remember.

Now I'm at work and I see. It is not including the tuple at the end of
the string nor using a dictionary. There is another way using locals().

I was trying to remember this method:

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.

Thanks
Matt


Matthew Pirritano, Ph.D.
Research Analyst IV
Medical Services Initiative (MSI)
Orange County Health Care Agency
(714) 568-5648
-----Original Message-----
From: tutor-bounces+mpirritano=ochca.com at python.org
[mailto:tutor-bounces+mpirritano=ochca.com at python.org] On Behalf Of
Steven D'Aprano
Sent: Saturday, September 17, 2011 6:58 PM
To: tutor at python.org
Subject: Re: [Tutor] string formatting

Matthew Pirritano wrote:

> 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"

Unless you use the string formatting operator %, strings containing "%" 
are just strings. Large or small, the way you do string formatting is 
with the % operator. Python will never do string formatting without an 
explicit command to do so:


text % value  # Single non-tuple argument
text % (value, value, ...)  # Multiple arguments


They don't have to be string literals, they can be variables:

text = "Hello, I'd like to have an %s"
value = "argument"
print text % value


You can also use named arguments by using a dictionary:

text = "Hello, I'd like to have an %(X)s"
values = {"X": "argument"}
print text % values

More details in the Fine Manual:
http://docs.python.org/library/stdtypes.html#string-formatting



Alternatives include the new advanced formatting method:

text.format()

http://docs.python.org/library/string.html#formatstrings


and "$" substitutions with the string module:

import string
string.Template

http://docs.python.org/library/string.html#template-strings





-- 
Steven

_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list