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.
Code
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: TrueFollowing 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
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.