14

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())

3 Answers 3

27

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}/"
3
  • 1
    Thanks, completely forgot locals().
    – Adam Matan
    Jul 4, 2013 at 13:55
  • note that '{a}'.format(**locals()), '{a}'.format(a=a) and '{0}'.format(a) are timed at 450ns, 410 and 215 respectivelly. (ok it's ns...)
    – comte
    May 11, 2015 at 16:44
  • note string interpolation (which is pretty awesome and works for the vast majority of use cases) will format immediately; in some cases (like template string arguments), you might want to call the format method at a later time, after initial string assignment Feb 21, 2019 at 3:10
2

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

0

less cryptic and faster

"my name is {__name__}".format_map(locals())

str.format_map(mapping)

Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.