Python Natural Sort (Alphanumeric Sort)


Natural sort order is an ordering of strings in alphabetical order, except that multi-digit numbers are ordered as a single character. Natural sort order has been promoted as being more human-friendly (“natural”) than the machine-oriented pure alphabetical order.

def atoi(text):
    return int(text) if text.isdigit() else text

def natural_keys(text):
    alist.sort(key=natural_keys) sorts in human order
    return [ atoi(c) for c in re.split('(\d+)', text) ]