Does Python have a built in function for string natural sort?
Question: Using Python 3.x, I have a list of strings for which I would like to perform a
natural alphabetical sort.

**Natural sort:** The order by which files in Windows are sorted.

For instance, the following list is naturally sorted (what I want):

    
    
    ['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
    

And here's the "sorted" version of the above list (what I have):

    
    
    ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']
    

I'm looking for a sort function which behaves like the first one.


Answer: Try this:

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

Output:

    
    
    ['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
    

See it working online: [ideone](http://ideone.com/W0HUe).

Code adapted from here: [Sorting for Humans : Natural Sort
Order](http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-
sort-order.html).

