Zet - How do f strings in python work compared to javascript template strings?

How do f strings in python work compared to javascript template strings?

Here’s a comparison between JavaScript template strings and Python f-strings in a table format:

FeatureJavaScript Template StringsPython f-strings
Syntax`Hello, ${name}!`f"Hello, {name}!"
Placeholder${expression}{expression}
String DelimitersBackticks (`)Double or single quotes (" or ')
Expression SupportAllows any valid JavaScript expressionAllows any valid Python expression
Multiline SupportNative multiline support with backticksNative multiline support with triple quotes (""" or ''')
Usage ContextCan be used wherever strings are used in JavaScriptCan be used wherever strings are used in Python
Variable SubstitutionSupports directly embedding variablesSupports directly embedding variables
Function CallsSupports embedding function callsSupports embedding function calls
Conditional LogicSupports ternary expressions within placeholdersSupports conditional logic within placeholders
EscapingUse \ to escape backticks or use regular quotesUse \ to escape double or single quotes

Example Code

JavaScript Template String:

const name = "Alice";
const age = 30;
console.log(`Hello, ${name}! You are ${age} years old.`);

Python f-string:

name = "Alice"
age = 30
print(f"Hello, {name}! You are {age} years old.")

Python f-strings and format strings: Automatically handle mixing numbers and strings. So this works.

#python #fstrings