<tutorialjinni.com/>

Python insert variable in string with curly braces

Posted Under: Programming, Python, Tutorials on Nov 6, 2024
Python insert variable in string with curly braces
In Python, you can use f-strings (formatted string literals) to insert variables into strings with curly braces {}. This is available in Python 3.6 and later.
Here's how you can do it:
name = "Alice"
age = 30
message = f"Hello, {name}. You are {age} years old."
print(message)
This is will be the output
Hello, Alice. You are 30 years old.
If you need to include curly braces {} in the string itself, you can double them {{ and }},
value = 42
message = f"The value is {{ {value} }}."
print(message)
Output look like this:
The value is { 42 }.
Alternatively, for versions before Python 3.6, you can use the .format() method:
name = "Alice"
age = 30
message = "Hello, {}. You are {} years old.".format(name, age)
print(message)
Or with named placeholders:
message = "Hello, {name}. You are {age} years old.".format(name="Alice", age=30)
print(message)


imgae