Groovy有一个GStrings的概念.我可以写这样的代码:
def greeting = 'Hello World'
println """This is my first program ${greeting}"""
Run Code Online (Sandbox Code Playgroud)
我可以从String中访问变量的值.
我怎么能用Python做到这一点?
- 谢谢
在Python中,您必须明确地传递可能变量的字典,您不能从字符串中访问任意"外部"变量.但是,您可以使用locals()返回包含本地范围的所有变量的字典的函数.
对于实际的替换,有很多方法可以做到(如何unpythonic!):
greeting = "Hello World"
# Use this in versions prior to 2.6:
print("My first programm; %(greeting)s" % locals())
# Since Python 2.6, the recommended example is:
print("My first program; {greeting}".format(**locals()))
# Works in 2.x and 3.x:
from string import Template
print(Template("My first programm; $greeting").substitute(locals()))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
766 次 |
| 最近记录: |