Python 中的 GString
Groovy 有一个 GString 的概念。 我可以编写这样的代码:
def greeting = 'Hello World'
println """This is my first program ${greeting}"""
我可以从字符串中访问变量的值。
我怎样才能在Python中做到这一点?
-- 谢谢
Groovy has a concept of GStrings. I can write code like this:
def greeting = 'Hello World'
println """This is my first program ${greeting}"""
I can access the value of a variable from within the String.
How can I do this in Python?
--
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在Python中,您必须显式传递可能变量的字典,您无法从字符串中访问任意“外部”变量。 但是,您可以使用
locals()
函数返回包含本地范围内所有变量的字典。对于实际的替换,有很多方法可以做到(多么不Python!):
In Python, you have to explicitely pass a dictionary of possible variables, you cannot access arbitrary "outside" variables from within a string. But, you can use the
locals()
function that returns a dictionary with all variables of the local scope.For the actual replacement, there are many ways to do it (how unpythonic!):
在 Python 2.6+ 中,您可以执行以下操作:
查看 PEP 3101。
In Python 2.6+ you can do:
Check out PEP 3101.
你不能完全...
我认为你真正能得到的最接近的是使用标准的基于%的替换,例如:
话虽如此,从Python 2.6开始有一些奇特的新类可以通过不同的方式做到这一点:查看2.6 的字符串文档,特别是从第 8.1.2 节开始,以了解更多信息。
You can't exactly...
I think the closest you can really get is using standard %-based substitution, e.g:
Having said that, there are some fancy new classes as of Python 2.6 which can do this in different ways: check out the string documentation for 2.6, specifically from section 8.1.2 onwards to find out more.
如果您尝试进行模板化,您可能需要研究一下 Cheetah。 它可以让你准确地做你所说的事情,相同的语法等等。
http://www.cheetahtemplate.org/
If your trying to do templating you might want to look into Cheetah. It lets you do exactly what your talking about, same syntax and all.
http://www.cheetahtemplate.org/