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
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
d = {'greeting': 'Hello World'}
print "This is my first program %(greeting)s" % d
You can't exactly...
I think the closest you can really get is using standard %-based substitution, e.g:
greeting = "Hello World"
print "This is my first program %s" % greeting
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.
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.
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!):
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()))