Last updated: Apr 9, 2024
Reading timeยท3 min
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.
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
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
.
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.
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.
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.
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.
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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: