Clever way of sorting strings containing integers?

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Thu Oct 9 04:57:39 EDT 2008


On Thu, 09 Oct 2008 00:41:27 -0700, Holger 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.

import re


def key_func(string):
    result = re.split(r'(\d+)', string)
    for i in xrange(1, len(result), 2):
        result[i] = int(result[i])
    return result


def main():
    lines = ['foo1bar2',
             'foo10bar10',
             'foo2bar3',
             'foo10bar2',
             'fo',
             'bar1000',
             '777']
    lines.sort(key=key_func)
    print '\n'.join(lines)


Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list