Python f-strings

Python's f-Strings, introduced in Python 3.6, provide a concise, readable, and powerful way to embed expressions within string literals. f-Strings are prefixed with an `f` or `F` and allow you to insert values and expressions inside curly braces `{}`, making it easy to dynamically construct strings.

1. Basic Syntax of f-Strings

The basic syntax for an f-String allows you to directly insert variable values into a string.

Example: Basic variable interpolation with f-Strings.
name = "Alice"
age = 30

# Using f-Strings to include variables in a string
greeting = f"Hello, my name is {name} and I am {age} years old."
print(greeting)

# Output: Hello, my name is Alice and I am 30 years old.

Output:
Hello, my name is Alice and I am 30 years old.

Explanation: Here, `f"Hello, my name is {name} and I am {age} years old."` includes the values of `name` and `age` directly within the string. The output confirms that the f-String interpolates the values correctly.

2. Expression Evaluation Inside f-Strings

f-Strings allow you to include expressions directly within the braces, providing greater flexibility.

Example: Performing calculations within an f-String.
x = 10
y = 5

# Using expressions within an f-String
result = f"The sum of {x} and {y} is {x + y}, and their product is {x * y}."
print(result)

# Output: The sum of 10 and 5 is 15, and their product is 50.

Output:
The sum of 10 and 5 is 15, and their product is 50.

Explanation: Here, `x + y` and `x * y` are evaluated directly within the f-String. The expressions are calculated before the string is displayed, allowing for dynamic calculations inside the string.

3. Formatting Numbers with f-Strings

You can use f-Strings to format numbers with specific decimal places or to include thousands separators.

Example: Formatting a floating-point number.
price = 1234.56789

# Formatting the number to two decimal places and adding a thousands separator
formatted_price = f"The price is ${price:,.2f}."
print(formatted_price)

# Output: The price is $1,234.57.

Output:
The price is $1,234.57.

Explanation: In this example, `{price:,.2f}` formats `price` to include a thousands separator (`,`) and rounds it to two decimal places (`.2f`). This ensures that `price` is displayed in a reader-friendly format.

4. Aligning and Padding Text

f-Strings support alignment and padding, making it easy to format text for reports or tables.

Example: Left-align, center-align, and right-align text with padding.
title = "Python"
left_aligned = f"|{title:<10}|"
center_aligned = f"|{title:^10}|"
right_aligned = f"|{title:>10}|"

print(left_aligned)
print(center_aligned)
print(right_aligned)

# Output:
# |Python    |
# |  Python  |
# |    Python|

Output:
|Python |
| Python |
| Python|

Explanation:
- `{title:<10}` left-aligns `title` within a width of 10.
- `{title:^10}` centers `title` within a width of 10.
- `{title:>10}` right-aligns `title` within a width of 10.

Each format specifies the alignment and width, producing a structured output.

5. Using f-Strings with Dictionaries

f-Strings can access values from dictionaries directly, making them useful for dynamically constructed strings.

Example: Accessing dictionary values with f-Strings.
person = {"name": "Bob", "age": 40}

# Accessing dictionary values in an f-String
description = f"{person['name']} is {person['age']} years old."
print(description)

# Output: Bob is 40 years old.

Output:
Bob is 40 years old.

Explanation: Here, `person['name']` and `person['age']` are accessed directly within the f-String, allowing for easy and readable dictionary value insertion.

6. Nesting f-Strings

You can nest f-Strings by assigning f-String expressions to variables and then using those variables in other f-Strings.

Example: Using a nested f-String.
name = "Charlie"
greeting = f"Hello, {name}"
message = f"{greeting}, welcome to the Python tutorial."

print(message)

# Output: Hello, Charlie, welcome to the Python tutorial.

Output:
Hello, Charlie, welcome to the Python tutorial.

Explanation: In this example, `greeting` is an f-String containing `name`, and `message` includes `greeting`. This approach shows how you can layer f-Strings to build up complex strings.

7. Conditional Expressions Inside f-Strings

f-Strings support conditional expressions, allowing you to include conditional logic directly within the string.

Example: Using a conditional expression in an f-String.
score = 85
result = f"You {'passed' if score >= 50 else 'failed'} the test."

print(result)

# Output: You passed the test.

Output:
You passed the test.

Explanation: In this example, the expression `{'passed' if score >= 50 else 'failed'}` determines the message based on `score`. The output shows that conditional logic is evaluated within the f-String.

8. Escaping Curly Braces

If you need to include literal curly braces `{}` in an f-String, you can escape them by doubling the braces.

Example: Displaying curly braces within an f-String.
# Escaping curly braces by doubling them
expression = f"The result of {{x + y}} is {10 + 5}"

print(expression)

# Output: The result of {x + y} is 15

Output:
The result of {x + y} is 15

Explanation: Here, `{{x + y}}` displays `{x + y}` as literal text, while `{10 + 5}` is evaluated as `15`. Doubling the curly braces lets you include them in the output.

9. Calling Functions Inside f-Strings

You can call functions directly within f-Strings to display their return values.

Example: Calling a function inside an f-String.
def greet(name):
    return f"Hello, {name}"

# Calling a function inside an f-String
message = f"{greet('Dana')}! Welcome to the course."

print(message)

# Output: Hello, Dana! Welcome to the course.

Output:
Hello, Dana! Welcome to the course.

Explanation: Here, `greet('Dana')` is called within the f-String, and its return value is included in `message`. This example demonstrates how you can integrate function calls within f-Strings for dynamic string construction.

10. Conclusion

f-Strings provide a powerful way to format strings with embedded expressions, function calls, conditional logic, and more. Their readability, conciseness, and versatility make them a go-to choice for dynamic string formatting in Python, allowing for a wide range of uses in both simple and complex scenarios.

Previous: Assignment Expressions | Next: Python venv

<
>