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 _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor