Alex Rivera | Logout

Python string interpolation using dictionary and strings

Asked 2009-08-20T04:54:16.110
25

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.

Edit
Report

1 Answer

5

You can do the following if you place your data inside a dictionary:

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

"{0}: {path}, {1}: {curr}, {2}: {prev}".format(*data, **data)
answered 2013-04-19T00:12:17.497

Your Answer