Home > Blockchain >  f-string formatting: display number sign?
f-string formatting: display number sign?

Time:12-17

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?

CodePudding user response:

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'

CodePudding user response:

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.

CodePudding user response:

You can use : in f-string

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

Output 3

CodePudding user response:

Like this:

numbers = [ 3, -3]

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

Result:

 3
-3

EDIT: Small time analysis:

import time

numbers = [ 3, -3] * 100

t0 = time.perf_counter()
[print(f"{number: }", end="") for number in numbers]
print(f"\n{time.perf_counter() - t0} s ")

t0 = time.perf_counter()
[print(f"{number: .2f}", end="") for number in numbers]
print(f"\n{time.perf_counter() - t0} s ")

t0 = time.perf_counter()
[print(f"{['', ' '][number>0]}{number}", end="") for number in numbers]
print(f"\n{time.perf_counter() - t0} s ")

Result:

f"{number: }"                    => 0.0001280000000000031 s
f"{number: .2f}"                 => 0.00013570000000000249 s
f"{['', ' '][number>0]}{number}" => 0.0001066000000000053 s

It looks like I have the fastest solution for integers.

CodePudding user response:

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

  • Related