F-strings, or formatted string literals, are a feature in Python introduced in version 3.6. They allow you to embed expressions inside string literals, using curly braces {}. To create an f-string, you prefix the string with the letter f or F.
Here's how f-strings work:
- Basic Usage: You can include variables directly in the string.
- Expressions: You can also include expressions that will be evaluated at runtime.
Example:
name = "Labby"
age = 3
greeting = f"Hello, my name is {name} and I am {age} years old."
print(greeting) # Output: Hello, my name is Labby and I am 3 years old.
Features:
- Readability: F-strings are often more readable than other formatting methods.
- Performance: They are generally faster than the older formatting methods like
%formatting orstr.format().
More Complex Expressions:
You can also perform operations within the curly braces:
x = 10
y = 5
result = f"The sum of {x} and {y} is {x + y}."
print(result) # Output: The sum of 10 and 5 is 15.
F-strings provide a powerful and convenient way to format strings in Python.
