An f-string, or formatted string literal, is a feature in Python that allows you to embed expressions inside string literals, using curly braces {}. This makes it easy to create strings that include variable values or expressions directly within the string.
Key Features of f-strings:
Syntax:
- An f-string is created by prefixing a string with the letter
forF. - Example:
name = "Alice" greeting = f"Hello, {name}!" # Outputs: "Hello, Alice!"
- An f-string is created by prefixing a string with the letter
Expression Evaluation:
- You can include any valid Python expression inside the curly braces, and it will be evaluated at runtime.
- Example:
age = 30 message = f"{name} is {age} years old." # Outputs: "Alice is 30 years old."
Formatting Options:
- You can format numbers, dates, and other types directly within the f-string.
- Example:
height = 1.75 formatted_string = f"Height: {height:.2f} meters" # Outputs: "Height: 1.75 meters"
Multi-line f-strings:
- f-strings can also span multiple lines using triple quotes.
- Example:
info = f""" Name: {name} Age: {age} """
Advantages of f-strings:
- Readability: They make the code easier to read and understand compared to older formatting methods (like
%formatting orstr.format()). - Performance: f-strings are generally faster than other string formatting methods because they are evaluated at runtime.
Example:
Here’s a complete example demonstrating the use of f-strings:
name = "John"
age = 25
height = 1.82
output = f"{name} is {age} years old and {height:.2f} meters tall."
print(output) # Outputs: "John is 25 years old and 1.82 meters tall."
If you have any further questions about f-strings or need more examples, feel free to ask!
