embed data inside string
John La Rooy
larooy at xtar.co.nz
Thu May 16 04:46:39 EDT 2002
On Thu, 16 May 2002 09:33:59 +0200
Matthias Baas <baas at ira.uka.de> 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 the other replies you've already seen how to use formatted strings
> which I would also consider to be the shortest way.
> However, if you really insist on not using formatted strings you can
> always use str() or repr():
>
> mystring = "Value of parameter = " + str(parameter) + " is unexpected"
>
> The difference between str() and repr() is that str() is supposed to
> return a string that's easy to read for humans whereas repr() should
> include all information to re-create the value from the string.
> As a shorthand for repr() you can use the ` apostrophes:
>
> mystring = "Value of parameter = " + `parameter` + " is unexpected"
>
> This makes the line almost as short as your original line.
>
> - Matthias -
>
Depends how badly you don't want to use formatted strings.
Perhaps this as a compromise?
mystring = "Value of parameter = %(parameter)s is unexpected"%vars()
otherwise you can
======
import re
parameter="something"
def perlish(s,vars):
return re.sub('\$(?P<parm>[a-zA-Z_].*?)\\b','%(\g<parm>)s',s)%vars()
print perlish('Value of parameter = $parameter is unexpected',vars)
=======
John
More information about the Python-list
mailing list