Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

252
Vistas
f-string formatting: display number sign?

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?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

From Docs:

  • Format Specification Mini-Language(Emphasis mine):
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.

  • 0 in Computer Science(Emphasis mine):

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.


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

over 4 years ago · Santiago Trujillo Denunciar

0

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.

over 4 years ago · Santiago Trujillo Denunciar

0

You can use :+ in f-string

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

Output +3

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda