Clever way of sorting strings containing integers?

Holger ishoej at gmail.com
Thu Oct 9 04:17:34 EDT 2008


On 9 Okt., 09:41, Holger <ish... at gmail.com> wrote:
> I tried to do this elegantly, but did not come up with a good solution
>
> Sort strings like
> foo1bar2
> foo10bar10
> foo2bar3
> foo10bar2
>
> So that they come out:
> foo1bar2
> foo2bar3
> foo10bar2
> foo10bar10
>
> I.e. isolate integer parts and sort them according to integer value.
>
> Thx
> Holger

or even:
foo1bar2
foo10bar10
foo2bar3
foo10bar2
fo
bar1000
777

To:
777
bar1000
fo
foo1bar2
foo2bar3
foo10bar2
foo10bar10

Here's my own take, but it doesn't quite work yet:
txtline = re.compile(r'(\D*)(\d+)')

lines = [x.strip() for x in sys.stdin.readlines()]
res = []
for l in [ x for x in lines if x]:
    groups = txtline.findall(l)
    res.append([[[x[0], int(x[1],0)] for x in groups],l])

res.sort()
for x in res:
    print x[1]



More information about the Python-list mailing list