Was ist der pythonischste Weg, um eine numerische Zeichenfolge mit Nullen auf der linken Seite aufzufüllen, d. h., damit die numerische Zeichenfolge eine bestimmte Länge hat?
Streicher:
>>> n = '4'
>>> print(n.zfill(3))
004
Und für Zahlen:
>>> n = 4
>>> print('%03d' % n)
004
>>> print(format(n, '03')) # python >= 2.6
004
>>> print('{0:03d}'.format(n)) # python >= 2.6 + python 3
004
>>> print('{foo:03d}'.format(foo=n)) # python >= 2.6 + python 3
004
>>> print('{:03d}'.format(n)) # python >= 2.7 + python3
004
>>> print(f'{n:03}') # python >= 3.6
004
Neben zfill
können Sie auch die allgemeine String-Formatierung verwenden:
print(f'{number:05d}') # (since Python 3.6), or
print('{:05d}'.format(number)) # or
print('{0:05d}'.format(number)) # or (explicit 0th positional arg. selection)
print('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection)
print(format(number, '05d'))
Dokumentation für string formatting und f-strings.
width = 10
x = 5
print "%0*d" % (width, x)
> 0000000005
In der Druckdokumentation finden Sie alle spannenden Details!
Aktualisierung für Python 3.x (7,5 Jahre später)
Die letzte Zeile sollte jetzt lauten:
print("%0*d" % (width, x))
D.h. print()
ist jetzt eine Funktion, keine Anweisung. Beachten Sie, dass ich immer noch den Old-School-Stil von printf()
bevorzuge, weil er sich IMNSHO besser liest, und weil ich diese Notation seit Januar 1980 verwende. Etwas ... alte Hunde ... etwas etwas ... neue Tricks.