How to insert variable values into a string in Python

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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds