Categories
Beginner Python

Cleaning Up Your Code with F-Strings in Python

Sure, sex is cool, but have you ever written efficient code that worked on the first try? F-strings are a great tool for writing clean, concise code. If you’re new to Python, or just looking for a quick refresher to clean up your code, save yourself some time and learn about f-strings.

What’s an f-string?

An f-string is a type of formatted Python string literal. It’s easily the most user-friendly Python feature I’ve encountered, and was a great confidence booster as a new programmer.


Here’s the basic format of an f-string:

print(f “[string] {placeholder1} {placeholder2}”)

It doesn’t look like much here, but it’s super helpful when working with numbers and multiple variables in a string.

Example program with an f-string:

Let’s say that you want to display a message that greets the user by name, and tells them how much they have left to spend from their budget that month.

What our code will display at the end: “Hi {user’s first name}! You’ve spent {x} dollars this month, and have {x} dollars left to spend.”

What we need to get from the user: Their first name, and the number of US dollars they spent this month

What we need to calculate: How many US dollars remain from the user’s $500 monthly budget

1. Our first step is to get the user’s first name.

#Get user’s first name
first_name = input(“What is your first name? “)

You probably already know that the variable first_name will reference any value the user enters. In this case, let’s say that one user enters their first name: Emily. Now, when you type in first_name, the program returns ‘Emily’.


2. Next, we’ll get the amount the user spent that month:

#Get amount spent (in US dollars)
dollars_spent = float(input(“How much did you spend this month (in US dollars)? “))

Let’s say that our user, Emily, enters 375.5. Now, the variable dollars_spent references the value ‘375.5’.
3.Finally, we will use the input value from the dollars_spent variable to calculate how much the user has left to spend this month. In this case, the program assumes the user has a budget of $500.00 a month. Therefore, it will subtract the dollars_spent variable from 500.00.

#Calculate dollars remaining
dollars_remaining = 500.00 — dollars_spent

Where the f-string comes in:


Since the first_name, dollars_spent, and dollars_remaining variables will change, you’ll put in what’s known as a ‘placeholder’ : a {set of brackets} containing a variable name.


Here’s what the code looks like so far:

first_name = input(“What is your first name? “)

User input → Emily

dollars_spent = float(input(“How much did you spend this month (in US dollars)? “))

User input → 375.5

dollars_remaining = 500.00 — dollars_spent
print(f”Hello, {first_name}! You have spent ${dollars_spent} this month, and have ${dollars_remaining} left to spend.”)

Output → Hello Emily! You have spent $375.5 this month, and have $124.5 left to spend.

Using these placeholders allows for multiple users to enter data and produce new output without repeating code. And, as we all know, efficient code is the best code.

The final step: formatting the number of decimal places our code displays.

$375.5 looks odd — let’s make sure our program displays two decimal places instead of one.To do this, we’ll simply add ‘:.2f’ to the dollars_spent and dollars_remaining placeholders.


Here’s what our completed code looks like:

print(f”Hello, {first_name}! You have spent ${dollars_spent:.2f} this month, and have ${dollars_remaining:.2f} left to spend.”)

New output → Hello, Emily! You have spent $375.50 this month, and have $124.50 left to spend.

Bottom line: save yourself some time and play around with f-strings. It will help clean up your coding style, and make your life easier. There is no consequence to messing up, and, as I mentioned in my previous article, you have to practice writing code to learn to write code. Happy coding!


Cleaning Up Your Code With F-Strings in Python was originally published in Level Up Coding on Medium.com. Read the original article here.