Using f-string for conditional formatting in Python

avatar

Borislav Hadzhiev

Last updated: Aug 30, 2022

banner

Photo from Unsplash

Using f-string for conditional formatting in Python #

Use a ternary operator to use f-strings for conditional formatting, e.g. result = f'{my_str.upper() if condition else my_str.lower()}'. The ternary operator will return the value to the left if the condition is met, otherwise the value to the right is returned.

main.py
my_str = 'hello' # ✅ f-string formatting with a condition result = f'Result: {my_str.upper() if len(my_str) > 1 else my_str.capitalize()}' print(result) # 👉️ Result: HELLO # ------------------------------------------ # ✅ Conditionally using format specification mini-language in f-strings my_num = 4.56789 result = f'The number is: {my_num:{".2f" if my_num > 1 else ""}}' print(result) # 👉️ The number is: 4.57 # ------------------------------------------ my_bool = True result = f'{my_num:{".2f" if my_bool else ""}}' print(result) # 👉️ 4.57
Make sure to alternate between single and double quotes if you have to. If you use nested quotes of the same type, you would terminate the string prematurely.

The examples use the ternary operator to check for conditions in f-strings.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: True

Make sure to wrap expressions in curly braces - {expression}.

The ternary operator is very similar to an inline if/else statement.

main.py
my_str = 'hello' result = f'Result: {my_str.upper() if len(my_str) > 1 else my_str.capitalize()}' print(result) # 👉️ Result: HELLO

The example checks if the length of the string is greater than 1 and if it is, the ternary operator calls the upper() method on the string and returns the result.

If the condition is not met, the else statement runs.

Here is a very simple example of using the ternary operator for check for a condition.

main.py
my_bool = True result = 'hello' if my_bool else 'bye' print(result) # 👉️ 'hello'

If the condition is met, the value to the left is returned, otherwise the value to the right is returned.

If you need to use the format-specific mini-language in an f-string, you have to use two sets of curly braces.

main.py
my_num = 4.56789 result = f'The number is: {my_num:{".2f" if my_num > 1 else ""}}' print(result) # 👉️ The number is: 4.57

Here is what the f-string would look like without a condition.

main.py
my_float = 4.56789 my_str_1 = f'{my_float:.2f}' print(my_str_1) # 👉️ 4.57

The first set of curly braces is used to evaluate the variable.

The inner set of curly braces uses the ternary operator to check for a condition.

A very important thing to note is that we are using single quotes to wrap the f-string and double quotes to wrap the strings within.

If you use nested quotes of the same type, you would get an error due to terminating the f-string string prematurely.

The following example checks if the my_bool variable stores a truthy value in the f-string.

main.py
my_num = 4.56789 my_bool = True result = f'{my_num:{".2f" if my_bool else ""}}' print(result) # 👉️ 4.57

If the my_bool variable stores a truthy value, the number gets formatted to 2 decimal places, otherwise an empty string is returned.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.