2010-08-17 11 views

Antwort

50

print "%02d"%a ist die Python-2-Variante

Python 3 verwendet eine etwas ausführlichere Formatierung System:

"{0:0=2d}".format(a) 

Die relevante doc Verbindung für python2 ist: http://docs.python.org/2/library/string.html#format-specification-mini-language

Für python3, dann ist es http://docs.python.org/3/library/string.html#string-formatting

+1

Die neue Python 3 Formatierung ist auch in 2.6 verfügbar, 2.7/3 erlaubt es Ihnen, ein etwas knapper mit Positionsargumenten. –

13
a = 5 
print '%02d' % a 
# output: 05 

Der ‚%‘ Operator genannt wird string formatting Operator, wenn sie mit einer Schnur auf der linken Seite eingesetzt. '%d' ist der Formatierungscode, um eine Ganzzahl auszudrucken (Sie erhalten einen Typfehler, wenn der Wert nicht numerisch ist). Mit '%2d können Sie die Länge angeben, und '%02d' kann verwendet werden, um das Füllzeichen auf 0 anstelle des Standardbereichs festzulegen.

1
>>> a=["%02d" % x for x in range(24)] 
>>> a 
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'] 
>>> 

Es ist so einfach

0

In Python3 können Sie:

print("%02d" % a) 
Verwandte Themen