How to Use f String in Python: Simple Guide with Examples
In Python, use
f"..." to create an f string, which lets you insert variables or expressions inside curly braces {} directly in the string. This makes string formatting simple and readable without extra functions.Syntax
An f string starts with the letter f or F before the opening quote. Inside the string, you put variables or expressions inside {}. Python replaces these with their values when the string runs.
- f"...": Marks the string as an f string.
- {variable}: Inserts the value of
variable. - {expression}: You can put any valid Python expression inside the braces.
python
name = "Alice" age = 30 message = f"My name is {name} and I am {age} years old." print(message)
Output
My name is Alice and I am 30 years old.
Example
This example shows how to use f strings to insert variables and do calculations inside the string easily.
python
price = 9.99 quantity = 5 total = price * quantity receipt = f"Price: ${price}, Quantity: {quantity}, Total: ${total:.2f}" print(receipt)
Output
Price: $9.99, Quantity: 5, Total: $49.95
Common Pitfalls
Some common mistakes when using f strings are:
- Forgetting the
fbefore the string, so variables won't be replaced. - Using single braces
{}incorrectly or forgetting to close them. - Trying to use backslashes inside expressions, which can cause errors.
python
name = "Bob" # Wrong: missing f before string message_wrong = "Hello, {name}!" print(message_wrong) # prints the literal text, not the variable # Right: message_right = f"Hello, {name}!" print(message_right)
Output
Hello, {name}!
Hello, Bob!
Quick Reference
Use this quick guide to remember how to use f strings:
| Feature | Usage Example | Description |
|---|---|---|
| Basic variable | f"Name: {name}" | Insert variable value inside braces |
| Expression | f"Sum: {a + b}" | Calculate inside braces |
| Format number | f"Price: {price:.2f}" | Format float to 2 decimals |
| Use quotes | f"He said, '{quote}'" | Mix quotes inside string |
| Multiline | f"""Line1 {var}\nLine2""" | Use triple quotes for multiline |
Key Takeaways
Always start the string with f or F to enable variable insertion.
Put variables or expressions inside curly braces {} to include their values.
You can format numbers and expressions directly inside the braces.
Without the f prefix, variables inside braces won’t be replaced.
Use f strings for clear, readable, and concise string formatting.