Last modified: Feb 07, 2025 By Alexander Williams

F-String in Python: A Beginner's Guide

Python's f-strings are a powerful way to format strings. They make your code cleaner and easier to read. This guide will help you understand how to use them effectively.

What is an F-String?

An f-string is a string literal that is prefixed with 'f' or 'F'. It allows you to embed expressions inside curly braces {}. These expressions are evaluated at runtime.

F-strings were introduced in Python 3.6. They are faster and more readable than older string formatting methods like % formatting or str.format().

Basic Syntax of F-Strings

The syntax is simple. Just add an 'f' before the string and place your variables or expressions inside curly braces.


name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")


My name is Alice and I am 30 years old.

In this example, {name} and {age} are replaced with their values at runtime.

Using Expressions in F-Strings

You can also use expressions inside f-strings. This makes them very flexible.


a = 5
b = 10
print(f"The sum of {a} and {b} is {a + b}.")


The sum of 5 and 10 is 15.

Here, the expression {a + b} is evaluated and the result is included in the string.

Formatting Numbers with F-Strings

F-strings can format numbers in various ways. You can control the number of decimal places, add commas, and more.


pi = 3.14159
print(f"Pi rounded to 2 decimal places: {pi:.2f}")


Pi rounded to 2 decimal places: 3.14

The :.2f inside the curly braces formats the number to two decimal places.

Using F-Strings with Dictionaries

You can also use f-strings with dictionaries. This is useful when you have multiple variables to include in a string.


person = {"name": "Bob", "age": 25}
print(f"{person['name']} is {person['age']} years old.")


Bob is 25 years old.

Here, the dictionary values are accessed using their keys inside the f-string.

Multiline F-Strings

F-strings can also be used with multiline strings. This is useful for creating longer, more complex strings.


name = "Charlie"
age = 40
message = (
    f"Name: {name}\n"
    f"Age: {age}\n"
    f"Status: {'Adult' if age >= 18 else 'Minor'}"
)
print(message)


Name: Charlie
Age: 40
Status: Adult

This example shows how to create a multiline f-string with embedded expressions.

Conclusion

F-strings are a powerful feature in Python. They make string formatting simple and efficient. By using f-strings, you can write cleaner and more readable code.

For more on Python strings, check out our guides on Variable vs String in Python and Python String Cast and Line Escape.

Start using f-strings in your Python projects today. They will save you time and make your code more elegant.