Python F-String Formatting

Sharing is caring!

Last Updated on July 23, 2022 by Jay

This tutorial will discuss using the Python f-string formatting, also called “formatted string literals.” F-string is a great and easy way to format strings, and it’s available for Python v3.6+. If you still use the .format() method for string formatting, you must check out f-string!

One of the advantages of using string formatting is the ability to “plug in” and format variables inside string data. We’ll see several examples of how to use it.

Python String format() Method vs F-string

The old way of string formatting is by using the .format() method. As shown below, we can insert variables into string-type data:

  • The curly brackets act as a placeholder for the variable.
  • The names (e.g. “a”, “b”) inside those curly brackets can be anything, they don’t have to be a and b – changing them to x and y will also work. They act like a keyword argument so we can choose where to insert the variables into the string.
num = '10'
var = 'apples'
s = 'i have {a} {b}'.format(a=num, b = var)
print(s)

i have 10 apples

The f-string became available with the release of Python v3.6. This new approach is much more powerful and intuitive than the old format() method. In order to use f-string, we need to:

  1. Start the string data with f, followed by the actual string.
  2. Similar to the old .format() method, we use curly brackets {} as placeholders for variables.
  3. We can insert variables directly into the curly brackets.

See the example below – it’s shorter to write and helps improve readability.

s = f'i have {num} {var}'
print(s)

i have 10 apples

Number format

We can use the f-string to manipulate different number formatting, such as controlling the decimal places, percentages, thousand delimiters, etc.

Decimal Place

Sometimes we might want to format a number, say keep two decimal places:

pi = 3.1415926
s = f'the value of pi is {pi:.2f}'  ##note the format ":.2f" will keep 2 decimal places
print(s)

the value of pi is 3.14

Percentage Formatting

We can also format numbers in percentages without needing to multiply a decimal number with 100 first.

a = 0.1234567
s = f'the percentage is {a:.3%}' ## ":.3" -> keep 3 decimals
print(s)

the percentage is 12.346%

Thousand Delimiters

In addition, we can also include thousand delimiters for number format data. Note that we are not limited to just the comma symbol – anything works except special symbols!

this_num = 69420
print(f'this number is {this_num:,}')
this number is 69,420


print(f'this number is {this_num:_}')
this number is 69_420

Thousand Delimiters and Decimals

Yes, we can have both thousand delimiters and decimal points simultaneously!

## add decimals
print(f'this number is {this_num:,.4f}')  ## :.4f to four decimal places
this number is 69,420.0000

Scientific Notation

To format a number with scientific notation, we just need to add :e (or :E) to the string formatting. To control the number of decimals. We just need to add a dot and a number in front of the e or E.

num = 1234567890
print(f'{num:e}')
print(f'{num:E}')
print(f'{num:.2e}')

1.234568e+09
1.234568E+09
1.23e+09

Date format

It’s also easy to format a datetime object’s string representation.

import datetime as dt
today = dt.datetime.today()
print(today)
2022-07-20 22:09:29.214792


print(f'today is {today:%Y/%m/%d}')
today is 2022/07/20

print(f'{today:%Y-%m}')  # year and month only
2022-07

Combine Python f-string With Raw String (r-string)

We can also combine the f-string and r-string. This technique is very useful for referencing files on our computer.

For example, we can decompose a file path into different sections and use variables to represent the path:

parent_dir = rf'C:\Users\jay\Desktop\PythonInOffice'
subfolder = 'string_formatting'
file_path = 'file01.xlsx'

print(rf'{parent_dir}\{subfolder}\{file_path }')
C:\Users\jay\Desktop\PythonInOffice\string_formatting\file01.xlsx

Text Alignment

It’s possible to align text by inserting blank spaces around both sides of string data.

  • To insert blank spaces on the left side of string, use :>n
  • To insert blank spaces on the right side of string, use :<n
  • Another possible way for right side insertion is just :n
  • For middle alignment, use :^n

The number of blank spaces will depend on both the n value we choose and the length of the string. If n is less than the length of the string, then this formatting will have no effect.

txt = 'python'        #6 characters long
print(f'{txt:>10}')   #10-6 = 4 blank spaces to fill on the left
print(f'{txt:<10}')   #fill blank on the right side of string
print(f'{txt:10}')    #fill blank on the right side of string
print(f'{txt:^10}')   #fill blank on both sides of string

    python
python    
python    
  python  

print(f'{txt:^0}')    #n less than string length, no effect 
python

Debugging Python Code with f-string

If you print variables for debugging, the f-string can help you too by reducing the code we need to type. See the below example – we just need to put the variable followed by an equal sign inside the curly brackets.

x = 100
print(f'{x = }')
x = 100

Using Conditions Inside Python F-string

We can also insert simple if/else conditions into an f-string. Consider the following example:

pass_mark = 50

mark_1 = 60
mark_2 = 49

print(f"student 1 {'pass' if mark_1 > pass_mark else 'fail'}")
print(f"student 2 {'pass' if mark_2 > pass_mark else 'fail'}")
student 1 pass
student 2 fail

Using Quotes Inside F-string

As the previous example shown, it’s possible to use quotes inside an f-string. The only rule is to match the opening and closing quotes with the same type, i.e. a single open quote needs to have a matching single close quote. Same with double quotes. This also implies that we can’t use the same quote symbol twice in the same f-string.

d = {'item':'apple'}
print(f'this is okay: {d["item"]}')
this is okay: apple

print(f"this is also okay: {d['item']}")
this is also okay: apple

print(f"same quotes won't work: {d["item"]}")
  Input In [53]
    print(f"same quotes won't work: {d["item"]}")
                                        ^
SyntaxError: f-string: unmatched '['

Calculation & functions/methods

Functions will be evaluated if we put them inside an f-string, which means we can use f-strings to display function results directly. Combining this with the previous debugging technique:

def add_two(x):
    return x+2

print(f'{add_two(1) =}')
add_two(1) =3

Multiple Line F-String

If the string is too long, we can divided it into multiple lines using three quotes “”” “”” instead of single quotes.

txt = 'this works'
print(f"""this is a long sentence
          with multiple lines. We 
          are using three quotes
          and {txt}""")

this is a long sentence
          with multiple lines. We 
          are using three quotes
          and this works

Performance

The Python f-string also appears to be slightly faster than the .format() method. We can test it using the %timeit built-in magic commands:

Python f-string performance
Python f-string performance

Additional Resources

Python for Office 101

Python raw string r-string

Leave a Reply

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