embed data inside string

Bengt Richter bokr at oz.net
Thu May 16 06:17:39 EDT 2002


On Thu, 16 May 2002 04:19:43 GMT, Julia Bell <juliabell at sbcglobal.net> wrote:

>I can create a string from a mixture of quoted strings and data with
>something like:
>mystring = "Value of parameter = " + parameter + " is unexpected"
>(where parameter is a variable holding a string value)
>Is there a way to embed the VALUE of the parameter in the string from
>within the quotes (essentially avoiding concatenating strings)?
>(I don't want to use formatted strings - I'm looking for something to
>simplify the line.)
>
>In perl I would have used:
>$mystring = "Value of parameter = $parameter is unexpected"
>(inside double quotes, the $parameter variable is evaluated, and it's
>value is embedded in the string)  I'm looking for something similar in
>python where I can refer to the value of the parameter inside a string.
>
>Julia Bell
>

    "%(someName)s" % vars()

will get someName from local variables and format it into the string with %s format,
e.g.,

 >>> parameter = '<the parameter string value>'
 >>> mystring = 'value of parameter = %(parameter)s is unexpected' % vars()
 >>> mystring
 'value of parameter = <the parameter string value> is unexpected'

you could also use other format specs for variables, and get them from an object,
e.g. %6.4f, and math respectively:

 >>> import math
 >>> math.pi
 3.1415926535897931
 >>> "pi is approximately %(pi)6.4f" % vars(math)
 'pi is approximately 3.1416'

See
    http://www.python.org/doc/current/lib/typesseq-strings.html
for more (which could be made easier to find IMO ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list