python sort strings with digits at the end

crosswired picture crosswired · Nov 30, 2010 · Viewed 9.3k times · Source

what is the easiest way to sort a list of strings with digits at the end where some have 3 digits and some have 4:

>>> list = ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> list.sort()
>>> print list
['asdf111', 'asdf123', 'asdf1234', 'asdf124']

should put the 1234 one on the end. is there an easy way to do this?

Answer

SethMMorton picture SethMMorton · Jan 15, 2015

is there an easy way to do this?

Yes

You can use the natsort module.

>>> from natsort import natsorted
>>> natsorted(['asdf123', 'asdf1234', 'asdf111', 'asdf124'])
['asdf111', 'asdf123', 'asdf124', 'asdf1234']

Full disclosure, I am the package's author.