[Tutor] Assigning multi line value to a variable

Steven D'Aprano steve at pearwood.info
Wed Jan 16 00:49:36 CET 2013


On 16/01/13 10:12, Rohit Mediratta wrote:
>
> Hi,
>     I am using Centos 6.3 and python 2.6.6.
>
> When I try to assign a variables value inside a multiple line message, it does not work.
>
>>>> cardName = "ActualCardName"
>>>> data = """<inst dn="root/child">
>          <card name=%cardName  descr="testingAgain">  """
>>>> print data
>   <inst dn="root/child">
>          <card name=%cardName  descr="testingAgain">
>
>
> I would like %cardName to be replaced by "actualCardName". As you can see
>  I am trying to use XML and therefore I will have several such replacements
>that I will need to do.


The error you show has nothing to do with "multiple line message", since it also doesn't work with a single line message:

py> x = "Hello"
py> msg = "%x"
py> print msg
%x


The way to fix this is the same regardless of whether the message is one line or a million lines. Python does not automatically substitute variables into strings, since that is a bad idea. However you can tell Python to substitute any values you like, using the % operator and string interpolation:

py> a = "spam"
py> b = "eggs"
py> msg = "Breakfast today is %s and %s."
py> print msg % (a, b)
Breakfast today is spam and eggs.


String interpolation codes include %s for strings, %d for integers, and %f for floats (among others).

You can also name the interpolation codes instead of substituting them by position:

py> values = {"bird": "parrot", "colour": "green"}
py> msg = "The %(colour)s %(bird)s ate the fruit."
py> print msg % values
The green parrot ate the fruit.


This leads to a clever trick: if you name the interpolation codes with the variable names you want, you can get the values of variables using the locals() function:


py> a = 42
py> b = "Hello World"
py> msg = "My variables include %(a)s and %(b)s."
py> print msg % locals()
My variables include 42 and Hello World.


More information about the string interpolation can be read here:

http://docs.python.org/2/library/stdtypes.html#string-formatting-operations

If you are familiar with C, you should find this very familiar.

Other alternatives include the string format method, and string templates:

http://docs.python.org/2/library/stdtypes.html#str.format
http://docs.python.org/2/library/string.html#template-strings

For example:

py> import string
py> msg = string.Template("My variables include $a and $b but not $c.")
py> print msg.safe_substitute(locals())
My variables include 42 and Hello World but not $c.



-- 
Steven


More information about the Tutor mailing list