Natural Sort Digit Aware Keys

Split digit runs out of names and compare them as integers, so report-2 sorts before report-10 and zero padding stops changing the order.

PythonData Integrity

Code

pythonsnippet
18 lines
import re

def natural_key(text):
    """Split digit runs out and compare them as integers, not characters."""
    parts = re.split(r"(\d+)", text)
    return [int(part) if part.isdigit() else part for part in parts]

files = ["report-10.csv", "report-2.csv", "report-1.csv", "summary.csv", "report-100.csv"]

# lexicographic order puts report-10 and report-100 before report-2
print("lexicographic:", sorted(files))
print("natural sort:  ", sorted(files, key=natural_key))

versions = ["v1.9", "v1.10", "v2.1", "v1.2"]
print("versions natural:", sorted(versions, key=natural_key))

# digit runs compare numerically, so zero padding does not matter
print("padded equals unpadded:", natural_key("a-007") == natural_key("a-7"))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

lexicographic: ['report-1.csv', 'report-10.csv', 'report-100.csv', 'report-2.csv', 'summary.csv']
natural sort:   ['report-1.csv', 'report-2.csv', 'report-10.csv', 'report-100.csv', 'summary.csv']
versions natural: ['v1.2', 'v1.9', 'v1.10', 'v2.1']
padded equals unpadded: True

Following the data

Natural Sort Digit Aware Keys comes down to the function natural_key.

The return value is newly constructed — inputs are never handed back.

Caveats

  • Self-sufficient — the runtime already provides whatever it imports.

Applying it

The entry-point signature is def natural_key(text)

The run prints lexicographic:, natural sort:, versions natural: — each prefix names the step that produced it.

Import natural_key from the file and call it — the rest of the code is implementation detail.

Statements that matter

def natural_key(text):
    """Split digit runs out and compare them as integers, not characters."""
    parts = re.split(r"(\d+)", text)
    return [int(part) if part.isdigit() else part for part in parts]

Interactive Tools for This Topic

FAQ

Does `natural_key` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `re`. The file defines `natural_key` at load time.