2

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

Parag
  • 12,093
  • 16
  • 57
  • 75

5 Answers5

5

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()))
Ferdinand Beyer
  • 64,979
  • 15
  • 154
  • 145
  • 2
    Note that the parens with print are a 3.0 newness; before print was a keyword, in 3.0 it's just a function like any other, so it needs the parens. This is why you see examples without them, in other answers. – unwind Apr 21 '09 at 07:14
  • print("My first program; {greeting}".format(**locals())) This last line gives me an error: AttributeError: 'str' object has no attribute 'format' – Parag Apr 21 '09 at 09:10
  • That's because you're not on 3.0 - the last example is 3.0-only. The preferred option in Python 2.x is the first example. – Carl Meyer Apr 21 '09 at 14:12
  • Ferdinand - please add Python version clarifications to your answer. Python 2.x is still much more widely used than 3.0. – Carl Meyer Apr 21 '09 at 14:13
  • @Carl: Thanks for the comment. I added the version hint -- note that str.format() is actually available since 2.6. – Ferdinand Beyer Apr 21 '09 at 15:39
  • Note that the s in %(greeting)s is for "string", not for making 'greeting' plural. ;) – endolith Jul 22 '09 at 01:26
3
d = {'greeting': 'Hello World'}
print "This is my first program %(greeting)s" % d
mhawke
  • 84,695
  • 9
  • 117
  • 138
2

In Python 2.6+ you can do:

"My name is {0}".format('Fred')

Check out PEP 3101.

pojo
  • 5,892
  • 9
  • 35
  • 47
1

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.

Wayne Koorts
  • 10,861
  • 13
  • 46
  • 72
1

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/

PKKid
  • 2,966
  • 3
  • 23
  • 20