[Tutor] How to numerically sort strings that start with numbers?

Peter Otten __peter__ at web.de
Tue Sep 14 09:43:56 CEST 2010


Pete O'Connell wrote:

> theList = ["21 trewuuioi","3zxc","134445"]
> print sorted(theList)
> 
> Hi, the result of the sorted list above doesn't print in the order I
> want. Is there a straight forward way of getting python to print
> ['3zxc','21 trewuuioi','134445']
> rather than ['134445', '21 trewuuioi', '3zxc']?

You have to write a function that extracts the number and use it as the key 
argument for sorted() or list.sort():

>>> import re
>>> def extract_number(s):
...     m = re.compile(r"-?\d+").match(s)
...     if m is not None:
...             return int(m.group())
...
>>> theList = ["21 trewuuioi","3zxc","134445"]
>>> sorted(theList, key=extract_number)
['3zxc', '21 trewuuioi', '134445']

Have a look as str.isdigit() if you want to write such a function without 
regular expressions.

Peter



More information about the Tutor mailing list