zero padded string
Hans Nowak
hnowak at cuci.nl
Thu Aug 23 11:07:27 EDT 2001
>===== Original Message From Max Møller Rasmussen <maxm at normik.dk> =====
>What is the simplest way to make a zero padded string usable for
>alphabetically sorting?
>
>This does it.
>
>number="42"
>print (8*'0')[:-len(number)] + number
>>> 00000042
>
>But my guess is that there is a builtin c-formatting that does it shorter.
>I'll be damned if I know what it is!
Do you mean something like this?
>>> '%09d' % 42
'000000042'
I assume this is what you want:
>>> z = ["0042", "0004", "4100"]
>>> z.sort()
>>> z
['0004', '0042', '4100']
and not:
>>> z = ["42", "4", "4100"]
>>> z.sort()
>>> z
['4', '4100', '42']
Or, if all strings are actually numbers, you can convert them to ints and sort
them:
>>> z = ["4", "42", "4100", "411"]
>>> z = map(int, z)
>>> z.sort()
>>> z
[4, 42, 411, 4100]
HTH,
--Hans Nowak
More information about the Python-list
mailing list