Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Python equivalent to template literals in JavaScript?

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.

like image 457
mikekoscinski Avatar asked Aug 31 '20 21:08

mikekoscinski


People also ask

What is a template in Python?

Template is a class of String module. It allows for data to change without having to edit the application. It can be modified with subclasses. Templates provide simpler string substitutions . Templates substitution is “$“-based substitutions.

What is template literal JavaScript?

Template literals are literals delimited with backtick ( ` ) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates.

Are template literals ES6?

Template Literals is an ES6 feature (JavaScript 2015).


1 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)
like image 103
Abhilash Avatar answered Oct 13 '22 20:10

Abhilash