Using f-string for conditional formatting in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
3 min

banner

# Using f-string for conditional formatting in Python

Use a ternary operator to use f-strings for conditional formatting.

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 = 'bobbyhadz.com' # โœ… f-string formatting with a condition result = f'Result: {my_str.upper() if len(my_str) > 1 else my_str.capitalize()}' print(result) # ๐Ÿ‘‰๏ธ Result: BOBBYHADZ.COM

using f string for conditional formatting

The code for this article is available on GitHub
Make sure to alternate between single and double quotes if you have to. If you use nested quotes of the same type, you will terminate the string prematurely.

The example uses 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 to 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.

# Using the format-specific mini-language conditionally in an f-string

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
The code for this article is available on GitHub

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

using f string without a condition

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.

# Alternate between single and double quotes

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 will 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

alternate between single and double quotes

The code for this article is available on GitHub

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

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev