Python formatted string literals are most commonly known as f-strings.

In Python, f-strings provide more simple and concise way to format strings than traditional string formatting. Python f-strings are faster than both %-formatting and str.format().

They are packed with lots of features that are handy in day-to-day use. Let’s have a look at what we are going to learn in this article.

Tricks and tips with python f-strings

  1. Display Variable Names
  2. Number Formatting
  3. Date Formatting
  4. Perform Mathematical Operations

Display Variable Names

In addition to displaying variable value, you can also display the variable name. This is very useful while debugging. You can do with by simply adding an equal (=) sign right after the variable name inside the curly braces.

Code

apples = 20
mangoes = 26
oranges = 22

print(f'We have: {apples = }, {mangoes = } and {oranges = }')
# We have: apples = 20, mangoes = 26 and oranges = 22

Number Formatting

You can also use f-string for formatting the numbers. All you need to do is, add colon (:) along with a format specifier. You can also display the variable name by adding equal sign in-between variable name and colon sign.

Best example for this would be trimming a floating point number to two digits right after the decimal by adding .2f format specifier.

Code

apple_price = 100/3

print(f'{apple_price:.2f}') # 33.33

# OR 

print(f'{apple_price = :.2f}') # apple_price = 33.33

Date Formatting

Python f-strings also allow us to format dates same as numbers. Just like number formatting, add a colon (:) along with a date format specifier. Same way, you can also display the variable name by adding an equal sign in-between variable name and colon sign in date formatting.

Basically, %d represents day of the month, %m represents month and %Y denotes the year.

Code

import datetime

date = datetime.date(2022, 2, 22)

print(f'{date = :%d-%m-%Y}') # date = 22-02-2022

For entire list of date formatting specifiers, click here.

Perform Mathematical Operations

With python f-strings, you can also perform mathematical operations by placing mathematical expressions inside the curly braces. You can also display the expression with results by placing an equal sign inside the curly braces.

Code

num = 22

if num % 2 == 0:
    print(f'{num = } is Even, because {num % 2 = }'.)
else:
    print(f'{num = } is Odd, because {num % 2 = }'.)

Till now, you got aware with Displaying Variable names, Number formatting, Date formatting and performing Mathematical operations with f-strings.

For more Python related posts, click here.

Categorized in: