There are three main methods for formatting strings in Python:
%-style formatting.format() methodHere's an overview of each method:
%-style formatting%-style formatting is the oldest method for formatting strings in Python. It uses the % operator to format a string with values. The syntax is as follows:
string % values |
For example:
name = "Alice"age = 25print("My name is %s and I am %d years old." % (name, age)) |
Output:
My name is Alice and I am 25 years old. |
.format() methodThe .format() method is a newer and more flexible method for formatting strings in Python. It uses curly braces {} as placeholders for the values. The syntax is as follows:
string.format(values) |
For example:
name = "Bob"age = 30print("My name is {} and I am {} years old.".format(name, age)) |
Output:
My name is Bob and I am 30 years old. |
f-strings, or formatted string literals, were introduced in Python 3.6. They provide a more concise and readable way to format strings, and are becoming increasingly popular. The syntax is as follows:
f'string {values}' |
For example:
name = "Charlie"age = 35print(f"My name is {name} and I am {age} years old.") |
Output:
My name is Charlie and I am 35 years old. |
All three methods have their advantages and disadvantages, and which one you choose will depend on your specific use case. However, the .format() method and f-strings are generally preferred over %-style formatting due to their increased flexibility and readability.