Yes, f-strings can be used with expressions in Python. You can include any valid Python expression inside the curly braces {} within an f-string. This allows you to perform calculations, call functions, or manipulate variables directly in the string.
Examples:
Basic Arithmetic:
a = 5 b = 10 print(f"The sum of {a} and {b} is {a + b}.")Output:
The sum of 5 and 10 is 15.Function Calls:
def square(x): return x * x num = 4 print(f"The square of {num} is {square(num)}.")Output:
The square of 4 is 16.Conditional Expressions:
temperature = 20 print(f"The weather is {'warm' if temperature > 15 else 'cold'}.")Output:
The weather is warm.Combining Variables and Expressions:
width = 5 height = 10 print(f"The area of the rectangle is {width * height}.")Output:
The area of the rectangle is 50.
Conclusion
F-strings provide a powerful and flexible way to format strings, allowing you to embed expressions directly, which enhances readability and reduces the need for additional formatting methods.
