F-Strings
F-strings, or formatted string literals, were introduced in Python 3.6 and provide a concise and readable way to embed expressions inside string literals. They are prefixed with f or F, and expressions to be inserted are placed inside curly braces {}.
Basic Syntax
The basic syntax for using f-strings is:
f"Text with a value {expression}"
- f: Prefix indicating that it is an f-string.
- {expression}: Python expression that will be evaluated and inserted into the string.
Example
name = "Alice" age = 30 message = f"Name: {name}, Age: {age}" print(message) # Output: Name: Alice, Age: 30
Expressions and Calculations
You can include expressions and calculations directly in an f-string:
a = 5 b = 10 result = f"The sum of {a} and {b} is {a + b}" print(result) # Output: The sum of 5 and 10 is 15
Number Formatting
F-strings allow you to use format specifiers to control the display of numbers:
Floating-Point Precision
pi = 3.14159265 formatted_pi = f"Pi to 2 decimal places: {pi:.2f}" print(formatted_pi) # Output: Pi to 2 decimal places: 3.14
Width and Alignment
number = 42 formatted_number = f"Number with width: {number:10} and {-number:<10}" print(formatted_number) # Output: Number with width: 42 and 42
Conditional Expressions
You can use conditional expressions within f-strings for greater flexibility:
temperature = 20 weather = "cool" if temperature < 15 else "warm" forecast = f"It is {weather} today." print(forecast) # Output: It is warm today.
Date Formatting
F-strings can also be used to format dates and times using methods from the datetime module:
from datetime import datetime now = datetime.now() formatted_date = f"Today is {now:%d-%m-%Y %H:%M}" print(formatted_date) # Output: Today is 28-07-2024 14:55
Accessing Object Attributes and Methods
F-strings can directly access attributes and methods of objects:
class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): return f"Hello, I'm {self.name}." person = Person("Alice", 30) greeting = f"{person.greet()} I am {person.age} years old." print(greeting) # Output: Hello, I'm Alice. I am 30 years old.
Formatting with Dictionaries and Lists
F-strings allow direct access to elements of dictionaries and lists:
Dictionaries
Person = {"name": "Alice", "age": 30} formatted_string = f"Name: {person['name']}, Age: {person['age']}" print(formatted_string) # Output: Name: Alice, Age: 30
Lists
values = ["Alice", 30] formatted_string = f"Name: {values[0]}, Age: {values[1]}" print(formatted_string) # Output: Name: Alice, Age: 30
Advantages of F-Strings
- Readability: The code is more readable and intuitive compared to older methods like str.format() and the % operator.
- Performance: F-strings are generally faster than str.format() because they are evaluated at runtime and are more efficient.
- Flexibility: You can embed complex expressions directly within f-strings.
Limitations and Considerations
- Python Versions: F-strings are available from Python 3.6 onwards. If you need to maintain code for earlier versions, you must use other formatting methods.
- Complex Expressions: While f-strings support complex expressions, excessive use can make the code harder to read.
Conclusion
F-strings are a modern and powerful feature for string formatting in Python. They provide a clear and efficient way to embed variables and expressions in strings, with precise control over the output format. Using f-strings can result in more readable and performant code, making them a preferred choice for many developers in Python 3.6 and newer.