Certainly! F-strings, or formatted string literals, are a way to embed expressions inside string literals in Python. They were introduced in Python 3.6 and provide a concise and readable way to format strings.
Syntax
An f-string is created by prefixing a string with the letter f or F. Inside the string, you can include expressions in curly braces {} that will be evaluated at runtime.
Example
Here's a simple example:
name = "Alice"
age = 30
greeting = f"Hello, {name}. You are {age} years old."
print(greeting)
Output
Hello, Alice. You are 30 years old.
Key Features
- Variable Interpolation: You can directly include variables and expressions.
- Expressions: You can perform calculations or call functions inside the curly braces:
result = f"The sum of 2 and 3 is {2 + 3}." print(result) # Output: The sum of 2 and 3 is 5. - Formatting Options: You can format numbers, dates, etc.:
pi = 3.14159 formatted_pi = f"Pi rounded to two decimal places: {pi:.2f}" print(formatted_pi) # Output: Pi rounded to two decimal places: 3.14
F-strings are generally preferred for their readability and efficiency compared to older formatting methods like % formatting or str.format().
If you have more questions or need further examples, feel free to ask!
