embed data inside string

Julia Bell julia.bell at jpl.nasa.gov
Thu May 16 10:23:24 EDT 2002


Thanks for all of the responses.

I recognize that the formatted strings are just as simple as the example line I gave
using the concatenation.   (I just used the simple example to demonstrate the point).
My actual application is more complex (lots of escaped characters, combination of
single and double quotes, etc. - just a messy string to be creating - so I was hoping
to at least eliminate the parts of the definition that involved leaving the quoted
portion to evaluate the parameter).

But, from the responses it looks like the concatenation I'm using is probably the
easiest way to go.

Thanks for the suggestions.

Julia Bell





Bengt Richter wrote:

> 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