Skip to content

Alphanumeric sorting

Ned Batchelder (the author of the coverage.py module) has a succinct alphanumeric sort:

import re

def tryint(s):
    try:
        return int(s)
    except:
        return s

def alphanum_key(s):
    """ Turn a string into a list of string and number chunks.
        "z23a" -> ["z", 23, "a"]
    """
    return [ tryint(c) for c in re.split('([0-9]+)', s) ]

def sort_nicely(l):
    """ Sort the given list in the way that humans expect.
    """
    l.sort(key=alphanum_key)

The result would be:


>>>alpha_num = ["a","1","100","a1","a10","9","b7","b8"]
>>>sort_nicely(alpha_num)
>>> alpha_num['1', '9', '100', 'a', 'a1', 'a10', 'b7', 'b8']

Be sure and check out the comments as there are a number of suggested improvements.