34

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.

mikekoscinski
  • 555
  • 1
  • 4
  • 14
  • 1
    You're after "format strings", see [here](https://docs.python.org/3/tutorial/inputoutput.html#fancier-output-formatting) – Robin Zigmond Aug 31 '20 at 22:00
  • Perfect, thank you. I actually just now found this & was coming back to close this. Future readers - this example could be solved w/ print(f'Hi, {name}, you are {age}') – mikekoscinski Aug 31 '20 at 22:04

1 Answers1

62

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)
Noelle L.
  • 100
  • 6
Abhilash
  • 2,026
  • 17
  • 21