[Tutor] string formatting

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


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.


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

Alternatives include the new advanced formatting method:



and "$" substitutions with the string module:

import string



Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:

More information about the Tutor mailing list