Python:使用变量名占位符格式化字符串
考虑以下字符串构建语句:
Consider the following string building statement:
s="svn cp %s/%s/ %s/%s/" % (root_dir, trunk, root_dir, tag)
使用四个 %s
可能会令人困惑,所以我更喜欢使用变量名:
Using four %s
can be confusing, so I prefer using variable names:
s="svn cp {root_dir}/{trunk}/ {root_dir}/{tag}/".format(**SOME_DICTIONARY)
当root_dir
、tag
和trunk
在类的作用域内定义时,使用self.__dict__
效果很好:
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.
当变量是本地变量时,如何使用变量名构造字符串?
更新:使用locals()
函数成功了.
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())