Sorting alphanumeric strings in Python

In a recent project, I had to sort a list of alphanumeric strings which looked like this:
[‘AL13, ‘AL3’, ‘AA14’, ‘AA4’]

My first thought was to use the sorted function, and that returned the following result:

>>> sorted([‘AL13, ‘AL3’, ‘AA14’, ‘AA4’])
[‘AA14’, ‘AA4’, ‘AL13’, ‘AL3’]

What I really wanted was it to give me back the list with the numbers sorted in a smarter way:

[‘AA4’, ‘AA14’, ‘AL3’, ‘AL13’]

After searching Stack Overflow, I found this post, which worked perfectly! See Mark Byers variation of Jeff Atwood’s natural sort.

Here’s the source reposted for reference:

import re
def sorted_nicely( l ):
    """ Sorts the given iterable in the way that is expected.

    Required arguments:
    l -- The iterable to be sorted.

    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
    return sorted(l, key = alphanum_key)