F-strings in Python provide a more concise and readable way to format strings compared to older methods. Here’s a comparison of f-strings with the older methods:
1. F-Strings (Python 3.6+)
F-strings are prefixed with f or F and allow you to embed expressions inside curly braces {} directly within the string.
Example:
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
2. str.format() Method
This method uses placeholders {} in the string and the format() function to replace them with values.
Example:
name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
3. Percent (%) Formatting
This is an older method that uses the % operator to format strings.
Example:
name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age))
Comparison
- Readability: F-strings are generally more readable and concise, especially for complex expressions.
- Performance: F-strings are faster than both
str.format()and%formatting because they are evaluated at runtime and do not require additional function calls. - Flexibility: F-strings allow for inline expressions, making it easy to perform calculations or method calls directly within the string.
Conclusion
F-strings are the preferred method for string formatting in modern Python due to their simplicity, performance, and readability.
