Python String Formatting: Insert Variables

In Python, you can insert variable values into strings using either the format() method or f-strings.

Using the format() method:

name = "Alice"
age = 30
sentence = "My name is {} and I am {} years old.".format(name, age)
print(sentence)

Use f-string:

name = "Alice"
age = 30
sentence = f"My name is {name} and I am {age} years old."
print(sentence)

Both methods allow for inserting variable values into strings. The f-string feature was introduced in Python 3.6 and above, making it more concise and convenient.

bannerAds