search

What is the use of the "format" method in Python?

The **format** method is used to format strings in Python. It replaces placeholders in a string with values specified as arguments. The placeholders can be defined using curly braces **{}** and they can be replaced by values using the **format** method or the **f** string literal syntax.

name = "John"
age = 30

# using format method
message = "My name is {} and I am {} years old".format(name, age)
print(message)  # My name is John and I am 30 years old

# using f-string
message = f"My name is {name} and I am {age} years old"
print(message)  # My name is John and I am 30 years old

Related Questions You Might Be Interested