Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is f' in Python

Understanding f' in Python: A Beginner's Guide

When you're just starting out with Python, you may come across lines of code that have an f before the quotation marks of a string. This f stands for "formatted string literal," commonly known as "f-string." But what does that mean, and how do you use it? Let's dive in and find out.

The Basics of f-strings

Imagine you're writing a birthday card and you want to include the person's name and age in the message. You could write out the entire message by hand, but what if you could write a template and just fill in the blanks with the person's details? That's essentially what f-strings do in Python.

An f-string allows you to embed expressions inside string literals, using curly braces {}. The expressions are replaced with their values.

Simple f-string Example

name = "Alice"
age = 30
greeting = f"Hello, {name}! You are {age} years old."
print(greeting)

When you run this code, it will output:

Hello, Alice! You are 30 years old.

The f-string f"Hello, {name}! You are {age} years old." takes the variables name and age and places their values into the string.

Incorporating Expressions

One of the powerful features of f-strings is that they can include actual Python expressions. You're not limited to just inserting variables; you can perform operations within the curly braces.

Expression in f-string

hours = 4
rate = 15
pay = f"Total pay: {hours * rate} dollars"
print(pay)

This will calculate the expression hours * rate and output:

Total pay: 60 dollars

Formatting Numbers

Sometimes you want to control how numbers are displayed. For instance, you may want to round a floating-point number to two decimal places or format a large number with commas. f-strings make this easy.

Formatting with f-strings

pi = 3.1415926535
number = 1234567.89
formatted_pi = f"Pi rounded to two decimal places: {pi:.2f}"
formatted_number = f"Formatted number with commas: {number:,.2f}"
print(formatted_pi)
print(formatted_number)

This will display:

Pi rounded to two decimal places: 3.14
Formatted number with commas: 1,234,567.89

Strings and Special Characters

When dealing with strings, you might want to include special characters like a newline or a tab. In f-strings, you can use backslash \ followed by the character you want to insert.

Newlines and Tabs in f-strings

name = "Bob"
hobby = "guitar"
profile = f"Name: {name}\nHobby: {hobby}\t(Level: Beginner)"
print(profile)

The \n inserts a newline, and the \t inserts a tab, resulting in:

Name: Bob
Hobby: guitar   (Level: Beginner)

Using Quotes Inside f-strings

What if you want to include a quote inside your f-string? You can mix single and double quotes to achieve this.

Quotes in f-strings

quote = f"Bob said, \"Python is fun!\""
print(quote)

This will print:

Bob said, "Python is fun!"

Alternatively, you could use single quotes around the f-string and double quotes inside, or vice versa.

Advanced Formatting

f-strings offer advanced formatting options, such as aligning text, padding, and more. Let's say you want to create a neatly aligned table of items and prices.

Advanced Formatting with f-strings

item1, price1 = "Apples", 0.67
item2, price2 = "Bananas", 1.49
print(f"{'Item':<10}{'Price':>10}")
print(f"{item1:<10}{price1:>10.2f}")
print(f"{item2:<10}{price2:>10.2f}")

In this example, < means align left, > means align right, and .2f formats the price to two decimal places. The output will be:

Item           Price
Apples          0.67
Bananas         1.49

Multiline f-strings

If you want to write an f-string that spans multiple lines, you can do so easily.

Multiline f-string Example

name = "Charlie"
age = 25
message = (
    f"Name: {name}\n"
    f"Age: {age}\n"
    f"Next year, you will be {age + 1}!"
)
print(message)

This will print:

Name: Charlie
Age: 25
Next year, you will be 26!

Debugging with f-strings

In Python 3.8 and above, you can even use f-strings to help with debugging by adding an = symbol after the expression. This will print both the expression and its value.

Debugging with f-strings

x = 3
y = 4
print(f"{x + y=}")

This will output:

x + y=7

Conclusion: The Beauty of Simplicity

As you can see, f-strings in Python are like a Swiss Army knife for string manipulation. They're straightforward yet powerful, allowing you to insert variables, perform calculations, and format strings with minimal effort. For beginners, mastering f-strings is like learning to write with a pen that never runs out of ink; it opens up a world of possibilities for expressing ideas clearly and concisely in code.

So next time you find yourself needing to craft a message, present data, or debug a tricky problem, remember the humble f-string. It's a simple tool, but with a little creativity, it can help you write Python code that is not just functional, but also elegant and expressive. Happy coding!