16

Basic question about python f-strings, but couldn't find out the answer: how to force sign display of a float or integer number? i.e. what f-string makes 3 displayed as +3?

1
  • Are you looking for a solution like a kind of row display? (Without any statement?) Commented Dec 17, 2021 at 10:56

5 Answers 5

24

From Docs:

Option Meaning
'+' indicates that a sign should be used for both positive as well as negative numbers.
'-' indicates that a sign should be used only for negative numbers (this is the default behavior).

Example from docs:

>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
'+3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'
>>> '{:+} {:+}'.format(10, -10)
'+10 -10'

Above examples using f-strings:

>>> f'{3.14:+f}; {-3.14:+f}'
'+3.140000; -3.140000'
>>> f'{3.14:-f}; {-3.14:-f}'
'3.140000; -3.140000'
>>> f'{10:+} {-10:+}'
'+10 -10'

One caveat while printing 0 as 0 is neither positive nor negative. In python, +0 = -0 = 0.

>>> f'{0:+} {-0:+}'
'+0 +0'
>>> f'{0.0:+} {-0.0:+}'
'+0.0 -0.0'

0.0 and -0.0 are different objects1.

In some computer hardware signed number representations, zero has two distinct representations, a positive one grouped with the positive numbers and a negative one grouped with the negatives; this kind of dual representation is known as signed zero, with the latter form sometimes called negative zero.

Update: From Python 3.11 and above, allows negative floating point zero as positive zero.

The 'z' option coerces negative zero floating-point values to positive zero after rounding to the format precision. This option is only valid for floating-point presentation types.

Example from PEP682:

>>> x = -.00001
>>> f'{x:z.1f}' '0.0'

>>> x = decimal.Decimal('-.00001')
>>> '{:+z.1f}'.format(x) '+0.0' 

1. Negative 0 in Python. Also check out Signed Zero (-0)

Sign up to request clarification or add additional context in comments.

Comments

5

You can use :+ in f-string

number=3
print(f"{number:+}")

Output +3

Comments

3

You can add a sign with an f-string using f"{x:+}", where x is the int/float variable you need to add the sign to. For more information about the syntax, you can refer to the documentation.

Comments

3

Fastest solution: f"{['', '+'][number>0]}{number}"

numbers = [+3, -3]

for number in numbers:
    print(f"{['', '+'][number>0]}{number}")

Result:

+3
-3

EDIT: Small time analysis:

import time

numbers = [+3, -3] * 1000000

t0 = time.perf_counter()
[print(f"{number:+}", end="") for number in numbers]
t1 = time.perf_counter()
[print(f"{number:+.2f}", end="") for number in numbers]
t2 = time.perf_counter()
[print(f"{['', '+'][number>0]}{number}", end="") for number in numbers]
t3 = time.perf_counter()
print("\n" * 50)
print("""number:+ : """ + str(round(t1-t0, 2)) + "s")
print("""number:+.2f : """ + str(round(t2-t1, 2)) + "s")
print("""['', '+'][number>0] : """ + str(round(t3-t2, 2)) + "s")

Result:

number:+ : 1.43s
number:+.2f : 1.98s
['', '+'][number>0] : 1.23s

It looks like I have the fastest solution for integers.

3 Comments

A bit cryptic, but I like this solution, using the result of number>0 as the index! Very clever.
clever and indeed cryptic. number>0 will evaluate to True or False. Python conveniently hard wires True to 1, and False to 0. ['', '+'][number>0] is thus a subscripted list, and the surrounding {} force evaluation.
Of note, this can also be used to place parenthesis (or anything else) around a negative number (financial etc) e.g. f"{['(', ''][n>=0]}{n:3.4}{[')', ''][n>=0]}" -> (-2.455) - I couldn't find any other way to do that.
-3

use if statement if x > 0: .. "" else: .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.