Python中的GStrings

Par*_*rag 2 python gstring

Groovy有一个GStrings的概念.我可以写这样的代码:

def greeting = 'Hello World'
println """This is my first program ${greeting}"""
Run Code Online (Sandbox Code Playgroud)

我可以从String中访问变量的值.

我怎么能用Python做到这一点?

- 谢谢

Fer*_*yer 5

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

  • 请注意,带有印花的parens是3.0新的; 在print是关键字之前,在3.0中它只是一个像其他任何函数一样的函数,所以它需要parens.这就是为什么你会看到没有它们的例子,在其他答案中. (2认同)