https://medium.com/@charliesharding/learning-python-no-template-literals-da7cbd77e3ba


Learning Python — Template Literals?

Charles Harding
Mar 11, 2017 · 1 min read

Coming from Javascript, python is a fairly approachable language. I’m going to try to keep up these posts as a reference for others learning python as well. One of the first things that I’ve encountered is the absence of template literals in the language.

In Javascript, one can type:

let age = 27;
console.log(`my age is ${age}!`);

And the output will be 'my age is 27!' . This is useful when you have a lot of embedded variables in a string so that you don’t have to keep concatenating with ending quotes and plus signs.

'lol ' + adversary.name + ' you suk at ' + adversary.favoriteThing + '!!!!111!11!'

I found an active proposal for this feature but it was posted two years ago. https://www.python.org/dev/peps/pep-0498/

Turns out they totally do exist, just under a different name and syntax.

x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)

The %s and % (varnames) is the way of inserting the values of those variables into the string. %s is used for strings whereas %d is used for numbers.

As pointed out in the comments by Phil Owens — a better functionality actually has been added in to python 3.6

“As of 3.6 you can use the syntax:

date = '22nd'txt = f"Today is March {date}."

Thanks Phil!

+ Recent posts