Is there a Python equivalent to template literals in JavaScript?

Question:

To provide a basic example, say I wanted to write:

name = str(input())
age = int(input())
print('Hi, {name}, you are {age}.')

In javascript, this would look like:

console.log(`Hi, ${name}, you are ${age}.`)

I assume there is no direct implementation of template literals in Python, as I haven’t found any mention on Google / DDG.

If I am correct in thinking that there isn’t a direct implementation, have any of you found workarounds? Thanks in advance.

Asked By: mikekoscinski

||

Answers:

You can go with formatted string literals ("f-strings") since Python 3.6

f"Hi {name}, you are {age}"

Or string formatting

"Hi {}, you are {}".format(name, age)
"Hi {name}, you are {age}".format(name=name, age=age)

Or format specifiers

"Hi %s, you are %d" % (name, age)
Answered By: Abhilash