Conditional string formatting in Python

avatar

Borislav Hadzhiev

Last updated: Aug 30, 2022

banner

Photo from Unsplash

Conditional string formatting in Python #

Use a ternary operator to implement conditional string 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 = 'alice' # ✅ conditional string formatting (f-string) result = f'Name: {my_str.upper() if len(my_str) > 1 else my_str.capitalize()}' print(result) # 👉️ Name: ALICE # ----------------------------------------------- # ✅ conditional string formatting (str.format()) result = 'Name: {}'.format(my_str.upper() if len( my_str) > 1 else my_str.capitalize()) print(result) # 👉️ Name: ALICE # ----------------------------------------------- # ✅ conditional string formatting (if/elif/else) result = f'Name: {"James Doe" if not my_str else my_str.upper() if len(my_str) > 1 else my_str.capitalize()}' print(result) # 👉️ Name: ALICE
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 when formatting strings.

The first example uses a formatted string literal.

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

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

The expressions have to be wrapped in curly braces - {expression}.

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

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 = 'Alice' if my_bool else 'Bob' print(result) # 👉️ 'Alice'

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

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.

You can also use the str.format() method to conditionally format strings.

main.py
my_str = 'alice' result = 'Name: {}'.format(my_str.upper() if len( my_str) > 1 else my_str.capitalize()) print(result) # 👉️ Name: ALICE

We used the ternary operator in the call to the str.format() method instead of using it inline in an f-string.

The str.format method performs string formatting operations.

The string the method is called on can contain replacement fields specified using curly braces {}.

Make sure to provide exactly as many arguments to the format() method as you have replacement fields in the string.

The examples above use a ternary operator to simulate an inline if/else statement.

If you have a more complex condition and need an if/elif/else statement, use a nested ternary.

main.py
my_str = 'alice' result = f'Name: {"James Doe" if not my_str else my_str.upper() if len(my_str) > 1 else my_str.capitalize()}' print(result) # 👉️ Name: ALICE

The first ternary operator checks if the my_str variable doesn't store a truthy value.

If the string is empty, the condition returns the string "James Doe", otherwise the else statement runs.

The else statement uses another ternary operator.

The nested ternary operator checks if the string's length is greater than 1 and converts it to uppercase if it is.

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.