How to correctly sort a string with a number inside?
Question: > **Possible Duplicate:**  
>  [Does Python have a built in function for string natural
> sort?](http://stackoverflow.com/questions/4836710/does-python-have-a-built-
> in-function-for-string-natural-sort)

I have a list of strings containing numbers and I cannot find a good way to
sort them.  
For example I get something like that:

    
    
    something1
    something12
    something17
    something2
    something25
    something29
    

with `sort()` method.

I know that I probably need to extract numbers somehow and then sort the list
but I have no idea how to do it in the most simple way.


Answer: Perhaps you are looking for [human
sorting](http://nedbatchelder.com/blog/200712/human_sorting.html) (also known
as [natural sorting](http://www.codinghorror.com/blog/2007/12/sorting-for-
humans-natural-sort-order.html)):

    
    
    import re
    
    def atoi(text):
        return int(text) if text.isdigit() else text
    
    def natural_keys(text):
        '''
        alist.sort(key=natural_keys) sorts in human order
        http://nedbatchelder.com/blog/200712/human_sorting.html
        (See Toothy's implementation in the comments)
        '''
        return [ atoi(c) for c in re.split('(\d+)', text) ]
    
    alist=[
        "something1",
        "something12",
        "something17",
        "something2",
        "something25",
        "something29"]
    
    alist.sort(key=natural_keys)
    print(alist)
    

yields

    
    
    ['something1', 'something2', 'something12', 'something17', 'something25', 'something29']
    

PS. I've changed my answer to use Toothy's implementation of natural sorting
(posted in the comments
[here](http://nedbatchelder.com/blog/200712/human_sorting.html)) since it is
significantly faster than my original answer.

