Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Formatting a string using variable names placeholders

Consider the following string building statement:

s="svn cp %s/%s/ %s/%s/" % (root_dir, trunk, root_dir, tag)

Using four %s can be confusing, so I prefer using variable names:

s="svn cp {root_dir}/{trunk}/ {root_dir}/{tag}/".format(**SOME_DICTIONARY)

When root_dir, tag and trunk are defined within the scope of a class, using self.__dict__ works well:

s="svn cp {root_dir}/{trunk}/ {root_dir}/{tag}/".format(**self.__dict__)

But when the variables are local, they are not defined in a dictionary, so I use string concatenation instead:

s="svn cp "+root_dir+"/"+trunk+"/ "+root_dir+"/"+tag+"/"

I find this method quite confusing, but I don't know any way to construct a string using in-line local variables.

How can I construct the string using variable names when the variables are local?

Update: Using the locals() function did the trick.

Note that mixing local and object variables is allowed! e.g.,

s="svn cp {self.root_dir}/{trunk}/ {self.root_dir}/{tag}/".format(**locals())
like image 505
Adam Matan Avatar asked Jul 04 '13 13:07

Adam Matan


2 Answers

You can use locals() function

s="svn cp {root_dir}/{trunk}/{root_dir}/{tag}/".format(**locals())

EDIT:

Since python 3.6 you can use string interpolation:

s = f"svn cp {root_dir}/{trunk}/{root_dir}/{tag}/"
like image 92
Kiro Avatar answered Sep 28 '22 09:09

Kiro


Have you tried s="svn cp {root_dir}/{trunk}/ {root_dir}/{tag}/".format(**locals()) ?

like image 37
yahe Avatar answered Sep 28 '22 09:09

yahe