Format Strings
In Python, string formatting allows you to create dynamic strings by embedding expressions or variables inside a string. There are several ways to format strings in Python, and one commonly used method is using the f-strings (formatted string literals).
1. F-strings (Formatted String Literals)
F-strings were introduced in Python 3.6 and provide a concise and readable way to embed expressions inside string literals.
name = "Alice"
age = 30
# Using f-string
message = f"My name is {name} and I am {age} years old."
print(message)
2. format()
Method
The format()
method is an older method for string formatting, available in Python 2.6 and 3.x. It uses placeholders {}
in the string, which are replaced by values provided to the format()
method.
name = "Bob"
age = 25
# Using format() method
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
3. String Concatenation
String concatenation involves using the +
operator to combine strings and variables.
name = "Charlie"
age = 22
# Using string concatenation
message = "My name is " + name + " and I am " + str(age) + " years old."
print(message)
Note: In the third example, str(age)
is used to convert the integer age
to a string before concatenation.
4. Older %
Formatting
The %
operator can also be used for string formatting. It is an older method and is less recommended than the f-strings or format()
method.
name = "David"
age = 28
# Using % formatting
message = "My name is %s and I am %d years old." % (name, age)
print(message)
5. Multiple Variables in f-strings
You can include multiple expressions and variables in an f-string.
first_name = "John"
last_name = "Doe"
age = 35
# Using f-string with multiple variables
full_message = f"My name is {first_name} {last_name} and I am {age} years old."
print(full_message)
Choose the string formatting method that you find most readable and convenient for your specific use case. F-strings are generally preferred for their clarity and simplicity when working with Python 3.6 and later versions.