October 13, 2024

F-Strings in Python

F-strings, introduced in Python 3.6, are a powerful and concise way to embed expressions inside string literals. The “f” in f-strings stands for “formatted,” and this feature allows you to include variables and expressions inside a string by prefixing the string with the letter f or F. F-strings provide a more readable and convenient way to format strings compared to older methods like % formatting or str.format().

Basic Usage of F-Strings

To create an f-string, simply prefix your string with f or F and include your variables or expressions inside curly braces {}.

Example: Basic F-String

name = "Alice"
age = 25

# Using f-strings to embed 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 25 years old.

Embedding Expressions in F-Strings

F-strings allow you to include not just variables, but also expressions inside the curly braces. You can perform calculations, call functions, or use any valid Python expression within an f-string.

Example: Embedding Expressions

num1 = 10
num2 = 5

# Performing calculations inside an f-string
result = f"The sum of {num1} and {num2} is {num1 + num2}."

print(result)

Output:

The sum of 10 and 5 is 15.

Formatting Numbers with F-Strings

F-strings support formatting options for numbers, such as specifying the number of decimal places, formatting as currency, or displaying in scientific notation.

Example: Formatting Numbers

pi = 3.141592653589793

# Formatting to two decimal places
formatted_pi = f"Pi rounded to two decimal places: {pi:.2f}"

# Formatting as currency
amount = 1234.56
formatted_amount = f"The amount is ${amount:,.2f}"

print(formatted_pi)
print(formatted_amount)

Output:

Pi rounded to two decimal places: 3.14
The amount is $1,234.56

Using F-Strings with Dictionaries and Lists

You can also use f-strings to access elements from dictionaries, lists, or any other data structure by including the appropriate index or key inside the curly braces.

Example: F-Strings with Dictionaries and Lists

person = {"name": "Alice", "age": 25}
numbers = [10, 20, 30]

# Accessing dictionary values
info = f"{person['name']} is {person['age']} years old."

# Accessing list elements
first_number = f"The first number in the list is {numbers[0]}."

print(info)
print(first_number)

Output:

Alice is 25 years old.
The first number in the list is 10.

Multiline F-Strings

You can create multiline f-strings by using triple quotes """ or ''' around the string. This is useful for formatting longer text blocks or when you want to include multiple lines of text in a single f-string.

Example: Multiline F-String

name = "Alice"
age = 25

# Creating a multiline f-string
info = f"""
Name: {name}
Age: {age}
"""

print(info)

Output:


Name: Alice
Age: 25

Escaping Braces in F-Strings

If you need to include literal curly braces in your f-string (for example, when working with formatted strings that include placeholders), you can escape them by doubling the braces {{}}.

Example: Escaping Braces

value = 42

# Escaping braces
escaped = f"The value is {{value}}."

print(escaped)

Output:

The value is {value}.

Conclusion

F-strings are a powerful and convenient feature in Python that simplify string formatting and make your code more readable. By using f-strings, you can easily embed variables, expressions, and formatted numbers within your strings, reducing the need for more complex and error-prone formatting methods.