building strings with variable input

Peter Otten __peter__ at web.de
Mon Jan 12 05:20:35 EST 2004


Olaf Meyer wrote:

> Sometimes if find it clumsy unsing the following approach building
> strings:
> 
> cmd = "%s -start %s -end %s -dir %s" % (executable, startTime, endTime,
> directory)
> 
> Especially if you have a lot of variable input it makes it hard to match
> the variables to the proper fields. From other scripting languanges I'm
> used to something like:
> 
>   $cmd = "$executable -start $startTime -end $endTime -dir $directory"
> 
> This makes it very easy to see how the string is actually built. You
> dont't have to worry where which variables go.
> 
> Is there a similar way to do this in python?

>>> "from %(org)s to %(dest)s" % dict(org="X", dest="Y")
'from X to Y'

or even

>>> org = "A"
>>> dest = "B"
>>> "from %(org)s to %(dest)s" % locals()
'from A to B'

Peter



More information about the Python-list mailing list