Skip to content

Python f-strings: Everything you need to know!

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!

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 = 32
name = Nik
fstring = 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 = 2
base = 3
fstring = 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:

                         apple
apple
            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.9124325345
print(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.9124325345
print(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.6457
print(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.6457
print(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.9124325345
print(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 = 2
print(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.

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

14 thoughts on “Python f-strings: Everything you need to know!”

  1. Pingback: Python: Reverse a String (6 Easy Ways) • datagy

  2. Pingback: Python: Reverse a List (6 Easy Ways) • datagy

  3. Pingback: Python Exponentiation: Use Python to Raise Numbers to a Power • datagy

  4. Pingback: Python Lowercase String with .lower(), .casefold(), and .islower() • datagy

  5. Pingback: Python: Combine Lists - Merge Lists (8 Ways) • datagy

  6. Pingback: Python Merge Dictionaries - Combine Dictionaries (7 Ways) • datagy

  7. Pingback: Python zfill & rjust: Pad a String in Python • datagy

  8. Pingback: Python: Concatenate a String and Int (Integer) • datagy

  9. I copied the below from this page. See the bottom of my Comments to see why…

    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 = 2
    base = 3
    fstring = f’The area of the triangle is {base*height/2}.’
    print(fstring)

    This returns:
    The height of the triangle is 3.
    +++++++++++++++++++++++++++++++++++
    In the last sentence the word ‘height’ should be ‘area’

  10. Broken link in this section “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.”

Leave a Reply

Your email address will not be published. Required fields are marked *