Saturday, April 30, 2011

GStrings in 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

From stackoverflow
  • 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.

    http://www.cheetahtemplate.org/

  • In Python 2.6+ you can do:

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

    Check out PEP 3101.

  • 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()))
    
    unwind : 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.
    Parag : print("My first program; {greeting}".format(**locals())) This last line gives me an error: AttributeError: 'str' object has no attribute 'format'
    Carl Meyer : 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 : Ferdinand - please add Python version clarifications to your answer. Python 2.x is still much more widely used than 3.0.
    Ferdinand Beyer : @Carl: Thanks for the comment. I added the version hint -- note that str.format() is actually available since 2.6.
    endolith : Note that the s in %(greeting)s is for "string", not for making 'greeting' plural. ;)

0 comments:

Post a Comment