Python f-strings: Everything you need to know! • datagy (2024)

Python f-strings, or formatted string literals, were introduced in Python 3.6. They’re called f-strings given that they are generated by placing an “f” in front of the quotation marks. What makes f-strings special is that they contain expressions in curly braces which are evaluated at run-time, allowing you large amounts of flexibility in how to use them!

Table of Contents

Video Tutorial

What are Python f-strings

Python f-strings (formatted string literals) were introduced in Python 3.6 via PEP 498. F-strings provide a means by which to embed expressions inside strings using simple, straightforward syntax. Because of this, f-strings are constants, but rather expressions which are evaluated at runtime.

How to write Python f-strings

You write Python f-strings by writing two parts: f (or F) and a string (either single, double, or triple quotes). So, an f-string can look like this:

fstring = f'string'

Where string is replaced by the string you want to use.

Displaying variables with f-strings

f-strings make it incredibly easy to insert variables into your strings. By prefacing your string with an f (or F), you can include variables by name inside curly braces ({}). Let’s take a look at an example:

age = 32name = Nikfstring = f'My name is {name} and I am {age} years old.'print(fstring)

This returns:

My name is Nik and I am 32 years old.

Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

Evaluating Expressions with Python f-strings

A key advantage of Python f-strings is the ability to execute expressions at runtime. What this means, is that you aren’t restricted to only inserting variable names. Similar to the example above, place your code into the string and it will execute as you run your program.

Let’s take a look at a basic example:

fstring = f'2 + 3 is equal to {2+3}'

This will return:

2 + 3 is equal to 5.

What’s more, is that you can even act on different variables within f-strings, meaning you can go beyond the use of constants in your expressions. Let’s take a look at another example:

height = 2base = 3fstring = f'The area of the triangle is {base*height/2}.'print(fstring)

This returns:

The area of the triangle is 3.

Accessing Dictionary Items with f-strings

Being able to print out dictionary values within strings makes f-strings even more powerful.

One important thing to note is that you need to be careful to not end your string by using the same type of quote. Let’s take a look at an example:

person1 = { 'name': 'Nik', 'age': 32, 'gender': 'male'}person2 = { 'name': 'Katie', 'age': 30, 'gender': 'female'}fstring = f'{person1.get("name")} is {person1.get("age")} and is {person1.get("gender")}.'print(fstring)

This returns:

Nik is 32 and is male.

Similarly, you can loop over a list of items and return from a list of dictionaries. Let’s give that a try!

person1 = { 'name': 'Nik', 'age': 32, 'gender': 'male'}person2 = { 'name': 'Katie', 'age': 30, 'gender': 'female'}people = [person1, person2]for person in people: print(f'{person.get("name")} is {person.get("age")} and is {person.get("gender")}.')

This returns:

Nik is 32 and is male.Katie is 30 and is female.

Conditionals in Python f-strings

Python f-strings also allow you to evaluate conditional expressions, meaning the result returned is based on a condition.

Let’s take a look at a quick, simple example:

name = 'Mary'gender = 'female'fstring = f'Her name is {name} and {"she" if gender == "female" else "he"} went to the store.'

This returns:

Her name is Mary and she went to the store.

This can be very helpful when you’re outputting strings based on (for example) values and want the grammar to be accurate. Let’s explore this with another example:

person1 = { 'name': 'Nik', 'age': 32, 'gender': 'male'}person2 = { 'name': 'Katie', 'age': 30, 'gender': 'female'}people = [person1, person2]

Say you wanted your text to specify he or she in a sentence depending on the person’s gender, you could write:

for person in people: print(f'{person.get("name")} is {person.get("gender")} and {"she" if person.get("gender") == "female" else "he"} is {person.get("age")} years old.')

This returns:

Nik is male and he is 32 years old.Katie is female and she is 30 years old.

Formatting Values with Python f-strings

It’s also possible to easily apply formatting to f-strings, including alignment of values and specifying number formats.

Specifying Alignment with f-strings

To specify alignment with f-strings, you can use a number of different symbols. In order to format strings with alignment, you use any of <, >, ^ for alignment, followed by a digit of values of space reserved for the string. In particular:

  • < Left aligned,
  • > Right aligned,
  • ^ Center aligned.

Let’s take a look at an example:

print(f'{"apple" : >30}')print(f'{"apple" : <30}')print(f'{"apple" : ^30}')

This returns:

 appleapple apple

This can be helpful to print out tabular formats

Formatting numeric values with f-strings

F-strings can also be used to apply number formatting directly to the values.

Formatting Strings as Percentages

Python can take care of formatting values as percentages using f-strings. In fact, Python will multiple the value by 100 and add decimal points to your precision.

number = 0.9124325345print(f'Percentage format for number with two decimal places: {number:.2%}')# Returns# Percentage format for number with two decimal places: 91.24%

Formatting Numbers to a Precision Point

To format numbers to a certain precision point, you can use the 'f' qualifier. Let's try an example to three decimal points:

number = 0.9124325345print(f'Fixed point format for number with three decimal places: {number:.3f}')# Returns# Fixed point format for number with three decimal places: 0.912

Formatting Numbers as Currency

You can use the fixed point in combination with your currency of choice to format values as currency:

large_number = 126783.6457print(f'Currency format for large_number with two decimal places: ${large_number:.2f}')# Returns# Currency format for large_number with two decimal places: $126783.65

Formatting Values with Comma Separators

You can format values with comma separators in order to make numbers easier to ready by placing a comma immediately after the colon. Let's combine this with our currency example and two decimal points:

large_number = 126783.6457print(f'Currency format for large_number with two decimal places and comma seperators: ${large_number:,.2f}')# Returns# Currency format for large_number with two decimal places and comma seperators: $126,783.65

Formatting Values with a positive (+) or negative (-) Sign

In order to apply positive (+) sign in front of positive values and a minus sign in front of negative values, simply place a + after the colon:

numbers = [1,-5,4]for number in numbers: print(f'The number is {number:+}')# Returns# The number is +1# The number is -5# The number is +4

Formatting Values in Exponential Notation

As a final example, let's look at formatting values in exponential notation. To do this, simply place an 'e' after the colon:

number = 0.9124325345print(f'Exponent format for number: {number:e}')# Returns# Exponent format for number: 9.124325e-01

Debugging with f-strings in Python

Beginning with Python 3.8, f-strings can also be used to self-document code using the = character.

This is especially helpful when you find yourself typing print("variable = ", variable) frequently to aid in debugging.

Let's try an example:

number = 2print(f'{number = }')

This would return:

number = 2

This can be especially useful when you find yourself debugging by printing a lot of variables.

Conclusion

f-strings are immensely valuable tool to learn. In this post, you learned how to use f-strings, including placing expressions into them, using conditionals within them, formatting values, and using f-strings for easier debugging.

Python f-strings: Everything you need to know! • datagy (2024)
Top Articles
Latest Posts
Recommended Articles
Article information

Author: Duane Harber

Last Updated:

Views: 5486

Rating: 4 / 5 (51 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Duane Harber

Birthday: 1999-10-17

Address: Apt. 404 9899 Magnolia Roads, Port Royceville, ID 78186

Phone: +186911129794335

Job: Human Hospitality Planner

Hobby: Listening to music, Orienteering, Knapping, Dance, Mountain biking, Fishing, Pottery

Introduction: My name is Duane Harber, I am a modern, clever, handsome, fair, agreeable, inexpensive, beautiful person who loves writing and wants to share my knowledge and understanding with you.