Python: formatting a string using alternate variable names

Consider the following line build statement:

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

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

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

When root_dir , tag and trunk defined within the 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 the 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 how to build a string using local local variables.

How can I build a string with variable names when the variables are local?

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

Please note that mixing local and object variables is allowed! eg.

 s="svn cp {self.root_dir}/{trunk}/ {self.root_dir}/{tag}/".format(**locals()) 
+7
python iterable-unpacking string-formatting
source share
2 answers

You can use locals() function

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

EDIT:

Starting with python 3.6 you can use string interpolation :

 s = f"svn cp {root_dir}/{trunk}/{root_dir}/{tag}/" 
+16
source share

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

+1
source share

All Articles