Python:使用变量名占位符格式化字符串 [英] Python: Formatting a string using variable names placeholders

查看:51
本文介绍了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_dirtagtrunk在类的作用域内定义时,使用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())

推荐答案

您可以使用 locals() 函数

You can use locals() function

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

从 python 3.6 开始,您可以使用 字符串插值:

Since python 3.6 you can use string interpolation:

s = f"svn cp {root_dir}/{trunk}/{root_dir}/{tag}/"

这篇关于Python:使用变量名占位符格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆