views:

634

answers:

4

Given:

dict = {"path": "/var/blah"}
curr = "1.1"
prev = "1.0"

What's the best/shortest way to interpolate the string to generate the following:

path: /var/blah curr: 1.1 prev: 1.0

I know this works:

str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % {"path": dict["path"],"curr": curr, "prev": prev}

But I was hoping there is a shorter way, such as:

str = "path: %(path)s curr: %s prev: %s" % (dict, curr, prev)

My apologies if this seems like an overly pedantic question.

+2  A: 

Maybe:

path = dict['path']
str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % locals()

I mean it works:

>>> dict = {"path": "/var/blah"}
>>> curr = "1.1"
>>> prev = "1.0"
>>> path = dict['path']
>>> str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % locals()
>>> str
'path: /var/blah curr: 1.1 prev: 1.0'

I just don't know if you consider that shorter.

hughdbrown
+2  A: 

Why not:

mystr = "path: %s curr: %s prev: %s" % (mydict[path], curr, prev)

BTW, I've changed a couple names you were using that trample upon builtin names -- don't do that, it's never needed and once in a while will waste a lot of your time tracking down a misbehavior it causes (where something's using the builtin name assuming it means the builtin but you have hidden it with the name of our own variable).

Alex Martelli
+2  A: 

You can try this:

data = {"path": "/var/blah",
        "curr": "1.1",
        "prev": "1.0"}

s = "path: %(path)s curr: %(curr)s prev: %(prev)s" % data
Triptych
+1  A: 

And of course you could use the newer (from 2.6) .format string method:

>>> mydict = {"path": "/var/blah"}
>>> curr = "1.1"
>>> prev = "1.0"
>>>
>>> s = "path: {0} curr: {1} prev: {2}".format(mydict['path'], curr, prev)
>>> s
'path: /var/blah curr: 1.1 prev: 1.0'

From the str.format() documentation:

This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in String Formatting Operations in new code.

monkut