[Tutor] string formatting

Steven D'Aprano steve at pearwood.info
Sun Sep 18 03:57:56 CEST 2011


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



More information about the Tutor mailing list