How do you perform string formatting in Python?
In Python, string formatting allows you to create strings with placeholders that are then replaced by actual values. There are several ways to perform string formatting in Python:
1. Using the `%` operator:
2. Using the `str.format()` method:
3. Using f-strings (formatted string literals) introduced in Python 3.6:
4. Using the `format()` function with curly braces `{}`:
Each method has its advantages, but f-strings are generally considered the most readable and concise way for string formatting in Python, especially in newer versions of the language.
1. Using the `%` operator:
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)
2. Using the `str.format()` method:
name = "Bob"
age = 25
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
3. Using f-strings (formatted string literals) introduced in Python 3.6:
name = "Charlie"
age = 35
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
4. Using the `format()` function with curly braces `{}`:
name = "David"
age = 40
formatted_string = "My name is {0} and I am {1} years old.".format(name, age)
print(formatted_string)
Each method has its advantages, but f-strings are generally considered the most readable and concise way for string formatting in Python, especially in newer versions of the language.