Format a number with a plus (+) sign in Python

avatar

Borislav Hadzhiev

Last updated: Sep 6, 2022

banner

Photo from Unsplash

Format a number with a plus (+) sign in Python #

Use a formatted string literal to format a number with a plus sign, e.g. result = f'{my_int:+}'. You can use an expression in the f-string to show the positive sign of the number.

main.py
# ✅ format integer with a plus sign my_int = 3479 result = f'{my_int:+}' print(result) # 👉️ +3479 # ----------------------------------- # ✅ format floating-point number with a plus sign my_float = 3.479567 result = f'{my_float:+.2f}' print(result) # 👉️ +3.48

We used a formatted string literal to format a number with a plus sign.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.
main.py
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print(result) # 👉️ 'bobbyhadz'

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 = 3479 result = f'{my_int:+}' print(result) # 👉️ +3479
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
num = 0 result = f'{num:{"+" if num 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
num = -3479 result = f'{num:{"+" if num else ""}}' print(result) # 👉️ -3479
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 format a floating-point number with a plus sign.

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

The first example formats the float with a plus sign and the second example formats it with a plus sign 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.