Print the sign of a number (+ or -) in Python

avatar

Borislav Hadzhiev

Last updated: Sep 6, 2022

banner

Photo from Unsplash

Print the sign of a number (+ or -) in Python #

Use a formatted string literal to print the sign of a number, e.g. print(f'{my_int:+}'). You can use an expression in the f-string to show the sign of the number for both positive and negative numbers.

main.py
# ✅ Print the plus or minus sign of an integer my_int = 124 result = f'{my_int:+}' print(result) # 👉️ +124 # ------------------------------------------ # ✅ Print the plus or minus sign of a float and round it to 2 decimals my_float = 3.456789 result = f'{my_float:+.2f}' print(result) # 👉️ +3.46

We used a formatted string literal to print the sign of a number.

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

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

Formatted string literals also enable us to use the format specification mini-language in expression blocks.

main.py
my_int = 124 result = f'{my_int:+}' print(result) # 👉️ +124
The plus sign after the colon indicates that a sign should be used for both positive and negative numbers.

The default behavior is to only show the sign of the number if it is negative.

If you don't want to show a sign if the number is zero, use the ternary operator.

main.py
my_int = 0 result = f'{my_int:{"+" if my_int else ""}}' print(result) # 👉️ 0

If the number is truthy, we return a string containing a plus, otherwise an empty string is returned.

Zero is the only number that is falsy, so a plus gets returned for any other value.

If the number is negative, a minus sign is shown.

main.py
my_int = -124 result = f'{my_int:+}' print(result) # 👉️ -124
The plus + sign after the colon indicates that the sign of the number should be shown, regardless if the number is positive or negative.

You can use the same approach to print the sign of floating-point numbers.

main.py
my_float = 3.456789 result = f'{my_float:+}' print(result) # 👉️ +3.456789 result = f'{my_float:+.2f}' print(result) # 👉️ +3.46

The first example prints the sign of the float and the second prints the sign of the float and rounds it to 2 digits after the decimal.

The digit after the period is the number of decimal places the float should have.

You can read about the format specification mini-language used in f-strings in this section of the docs.

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.