Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GStrings in Python

Tags:

python

gstring

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

like image 687
Parag Avatar asked Jan 22 '26 13:01

Parag


1 Answers

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()))
like image 78
Ferdinand Beyer Avatar answered Jan 24 '26 02:01

Ferdinand Beyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!