Combinación de formatos de cadena
Frecuentes
Visto 1,678 veces
2
Estoy tratando de usar .format()
to format my output. I am trying to align the float to be centered, occupy a width of 12 and only display 2 decimal points.
I already have it working to be centered and occupy a width of 12 as follows:
print "{:^12}".format(dig)
However, how do I add the two decimal places format into this? I know it's .2f
, but how do I combine it all? I tried adding it after the 12, before the :
and at all sorts of places - it would always throw back an error.
¡Gracias!
2 Respuestas
8
Sólo tiene que utilizar 12.2f
:
>>> print "|{:^12.2f}|".format(145.6798)
| 145.68 |
usado |
just to prove that the 12
width is working.
Respondido el 23 de Septiembre de 13 a las 02:09
1
Aquí está la documentación para especificación de formato:
dig = 22/7.0 # 3.142857142857143
print "->123456789012<-"
print "->{:^12.2f}<-".format(dig) # using .2f as you expected
^^^
Te regalaré
->123456789012<-
-> 3.14 <-
Respondido 25 ago 12, 03:08
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas python string format or haz tu propia pregunta.
For future reference, you can find the documentation on format specifications here: docs.python.org/library/string.html#formatspec - Liquid_Fire