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:
| Feature | JavaScript Template Strings | Python f-strings |
|---|---|---|
| Syntax | `Hello, ${name}!` | f"Hello, {name}!" |
| Placeholder | ${expression} | {expression} |
| String Delimiters | Backticks (`) | Double or single quotes (" or ') |
| Expression Support | Allows any valid JavaScript expression | Allows any valid Python expression |
| Multiline Support | Native multiline support with backticks | Native multiline support with triple quotes (""" or ''') |
| Usage Context | Can be used wherever strings are used in JavaScript | Can be used wherever strings are used in Python |
| Variable Substitution | Supports directly embedding variables | Supports directly embedding variables |
| Function Calls | Supports embedding function calls | Supports embedding function calls |
| Conditional Logic | Supports ternary expressions within placeholders | Supports conditional logic within placeholders |
| Escaping | Use \ to escape backticks or use regular quotes | Use \ 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