Comparison of format() Function and f-Strings
The f-string
and format()
function are useful Python syntax for string formatting.
Let's summarize how each syntax is used and what characteristics they have.
format Function
The format()
function inserts variables into a string using curly braces {}
.
Example of using format() function
name = "CodeBuddy"
age = 20
# Using the format() function
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
You can specify the order of variables using {index}
.
Example of using index with format() function
"I am {1} years old and my name is {0}.".format(name, age)
# Output: I am 20 years old and my name is CodeBuddy.
f-Strings
f-strings
use f
or F
before the string and allow you to include variables or expressions directly inside curly braces {}
.
name = "CodeBuddy"
age = 20
# Using f-strings
message = f"My name is {name} and I am {age} years old."
print(message)
Features:
- You can include variable names, expressions, and function calls directly inside the curly braces
{}
. - It is concise and improves code readability.
width = 5
height = 3
print(f"The area of the rectangle is {width * height}.") # Output: The area of the rectangle is 15.
Comparison of format()
Function and f-Strings
Feature | format() Function | f-Strings |
---|---|---|
Python Version | Python 2.7 and above | Python 3.6 and above |
Usage | Requires .format() function call | Use f before the string and curly braces {} |
Expressions | Not possible (only variables) | Possible (arithmetic operations, function calls, etc.) |
Flexibility | Suitable for dynamic formatting, where the number or position of variables may change | Suitable for simple formatting and quick expressions |
Tip: In most modern Python projects,
f-strings
are recommended!
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.