简体   繁体   中英

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.

You can go with 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM