How to Use f String Expression in Python: Simple Guide
In Python, you use an
f string by prefixing a string with f or F and placing expressions inside curly braces {}. This lets you embed variables or calculations directly in the string for clear and concise output.Syntax
An f string starts with the letter f before the opening quote. Inside the string, you put expressions or variables inside {}. Python evaluates these expressions and inserts their values into the string.
f"...{expression}...": The basic format.expression: Can be a variable, math operation, or function call.- Supports all Python expressions inside the braces.
python
name = "Alice" age = 30 message = f"Hello, {name}. You are {age} years old." print(message)
Output
Hello, Alice. You are 30 years old.
Example
This example shows how to use f strings to combine variables and expressions inside a string. It prints a greeting and calculates the year of birth.
python
name = "Bob" age = 25 current_year = 2024 print(f"Hi {name}, you will be {age + 1} next year.") print(f"You were born in {current_year - age}.")
Output
Hi Bob, you will be 26 next year.
You were born in 1999.
Common Pitfalls
Common mistakes when using f strings include:
- Forgetting the
fprefix, so expressions are not evaluated. - Using single braces
{}incorrectly or forgetting to close them. - Trying to use backslashes inside expressions, which can cause errors.
Always ensure the string starts with f and expressions are valid Python code.
python
name = "Eve" # Wrong: missing f prefix, prints literal braces print("Hello, {name}!") # Right: with f prefix, evaluates expression print(f"Hello, {name}!")
Output
Hello, {name}!
Hello, Eve!
Quick Reference
| Feature | Description | Example |
|---|---|---|
| Prefix | Start string with f or F | f"Hello" |
| Expression | Put Python code inside {} | f"{2 + 3}" |
| Variables | Insert variable values | f"{name}" |
| Functions | Call functions inside {} | f"{len(name)}" |
| Format Spec | Format numbers or dates | f"{value:.2f}" |
Key Takeaways
Always start the string with an f to enable expression evaluation.
Place any valid Python expression inside curly braces {} to embed it.
f strings make code cleaner and easier to read than older formatting methods.
Watch out for missing the f prefix, which causes expressions to be shown literally.
You can format numbers and call functions directly inside f strings.