How to use Conditional Formatting with f-Strings in Python
Python's f-strings (formatted string literals) provide a powerful way to embed expressions and variables directly within strings.
This guide explains how to use conditional logic (ternary operators) within f-strings to dynamically format output based on conditions.
Basic Conditional Formatting with Ternary Operators
The core concept is to use a ternary operator (also known as a conditional expression) inside the f-string's curly braces {}:
my_str = 'tutorialreference.com'
result = f'Result: {my_str.upper() if len(my_str) > 1 else my_str.capitalize()}'
print(result) # Output: Result: TUTORIALREFERENCE.COM
- The ternary operator
my_str.upper() if len(my_str) > 1 else my_str.capitalize()will first evaluate the boolean value oflen(my_str) > 1.
The f-string f'Result: { }' embeds the result of a ternary operator (conditional expression). The general form is:
f'{ <value_if_true> if <condition> else <value_if_false> }'
In this example:
- Condition:
len(my_str) > 1(checks if the string length is greater than 1) - Value if True:
my_str.upper()(converts the string to uppercase) - Value if False:
my_str.capitalize()(capitalizes the first letter)
Here is another simple example:
my_bool = True
result = 'hello' if my_bool else 'bye'
print(result) # Output: hello
- If the condition is
True, the ternary returns the value to the left, and if it'sFalseit returns the value to the right.
Conditional Formatting with Numerical Values
You can combine conditional logic with f-string's formatting capabilities for numbers:
my_num = 4.56789
result = f'The number is: {my_num:.2f}' # Standard formatting, 2 decimal places
print(result) # Output: The number is: 4.57
my_num = 4.56789
result = f'The number is: {my_num:.2f if my_num > 1 else ""}' # Conditional formatting
print(result) # Output: The number is: 4.57
f'{my_num:{".2f" if my_num > 1 else ""}}'
- The outer curly braces
{}are for the f-string. - The inner curly braces
{}are for the format specifier. - The ternary operator
".2f" if my_num > 1 else ""chooses the format string based on the value ofmy_num. Ifmy_numis greater than 1 it will use the.2f, otherwise it will return an empty string.
Quoting and Escaping within f-strings
When using string literals within an f-string's expression, be careful with quoting:
- Alternate quote types: If your f-string is enclosed in double quotes (
"), use single quotes (') inside the expression (and vice-versa). This is the best and most readable approach.
my_num = 4.56789
my_bool = True
result = f'{my_num:".2f" if my_bool else ""}' # Correct: single quotes in f-string
print(result) # Output: 4.57