Skip to content

Instantly share code, notes, and snippets.

@signed0
Created February 10, 2012 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save signed0/1787885 to your computer and use it in GitHub Desktop.
Save signed0/1787885 to your computer and use it in GitHub Desktop.
Python natural sort key
# Inspired by http://code.activestate.com/recipes/285264-natural-string-sorting/
import re
digits = re.compile(r'(\d+|\D+)')
def natural_sort_key(item):
if item is None or item == '':
return None
pieces = digits.findall(item)
pieces = (int(i) if i.isdigit() else i for i in pieces)
return tuple(pieces)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment