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)

FAQs

What do f-strings do in Python? ›

F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces.

What are the limitations of F-strings in Python? ›

Python 3.12's F-Strings Still Have Some Limitations

Otherwise, the f-string won't work. In these examples, you use a colon as part of the syntax of a lambda function. This function is useless because there's no way to call it. This code fails on both Python 3.11 and 3.12.

How to escape {} in Python f-string? ›

Python f-string Escaping Characters

For this purpose, we make use of escape characters in f-string. To escape a curly bracket, we double the character. While a single quote is escaped using a backslash.

Should you always use F-strings? ›

Using f-strings, your code will not only be cleaner but also faster to write. With f-strings you are not only able to format strings but also print identifiers along with a value (a feature that was introduced in Python 3.8).

Why are F strings faster? ›

F-strings are faster than str. format() because f-strings are evaluated at compile-time rather than at runtime. When you use an f-string, the expression inside the curly braces is evaluated at compile-time, and the resulting value is inserted into the string.

What are the advantages of F-string? ›

Advantages of f-strings

* Enhanced Code Readability and Maintainability: F-strings improve code readability and maintainability by offering a more natural and concise syntax. The ability to embed expressions directly within the string reduces the need for complex concatenation or placeholder manipulation.

Are Python F-strings secure? ›

For example, f-strings have similar syntax to str. format() but, because f-strings are literals and the inserted values are evaluated separately through concatenation-like behavior, they are not vulnerable to the same attack (source B).

Why not use F-string in logging Python? ›

Using f-strings to format a logging message requires that Python eagerly format the string, even if the logging statement is never executed (e.g., if the log level is above the level of the logging statement), whereas using the extra keyword argument defers formatting until required.

What operators Cannot be used with strings in Python? ›

Arithmetic operators that cannot be used with strings in Python include division (/), modulo (%), and exponentiation (**). These operators are designed for numerical operations and are not applicable to strings. Strings in Python are treated as sequences of characters and do not support mathematical operations.

When did Python add f strings? ›

Python f-strings or formatted strings are the new way to format strings. This feature was introduced in Python 3.6 under PEP-498.

How do you set precision in F-string in Python? ›

F-strings can also be used to round numbers to a specific precision, using the round() function. To round a number using f-strings, simply include the number inside the curly braces, followed by a colon and the number of decimal places to round to.

How do you single quote an F-string in Python? ›

We can use any quotation marks {single or double or triple} in the f-string. We have to use the escape character to print quotation marks. The f-string expression doesn't allow us to use the backslash. We have to place it outside the { }.

What does F mean in a string? ›

F Strings are just a shorthand for str. format - and while they are convinient, they can't do a lot of things that str. format can. For example, with str. format , you can fetch the format string from somewhere (maybe user input / config) and then format your input using that format string.

What does .2f mean in Python? ›

In Python, the . 2f format specifier is used to format floating-point numbers as strings with two decimal places. This format specifier is part of the Python strings format syntax in Python.

What is the F string concatenation in Python? ›

String Concatenation using f-string

It's a new way to format strings and introduced in PEP 498 - Literal String Interpolation. Python f-string is cleaner and easier to write when compared to format() function. It also calls str() function when an object argument is used as field replacement.

Are Python F strings secure? ›

For example, f-strings have similar syntax to str. format() but, because f-strings are literals and the inserted values are evaluated separately through concatenation-like behavior, they are not vulnerable to the same attack (source B).

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Moshe Kshlerin

Last Updated:

Views: 6364

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Moshe Kshlerin

Birthday: 1994-01-25

Address: Suite 609 315 Lupita Unions, Ronnieburgh, MI 62697

Phone: +2424755286529

Job: District Education Designer

Hobby: Yoga, Gunsmithing, Singing, 3D printing, Nordic skating, Soapmaking, Juggling

Introduction: My name is Moshe Kshlerin, I am a gleaming, attractive, outstanding, pleasant, delightful, outstanding, famous person who loves writing and wants to share my knowledge and understanding with you.