Natural Sorting for Python

8.4.0 · active · verified Sun Mar 29

natsort is a Python library that provides 'natural' sorting capabilities, enabling lists containing numbers (e.g., filenames, version strings) to be sorted numerically rather than strictly lexicographically. It's a versatile tool that handles various data types and offers extensive customization. The current version is 8.4.0, and the library is actively maintained with a regular release cadence.

Warnings

Install

Imports

Quickstart

Demonstrates the basic usage of `natsorted()` to naturally sort a list of strings containing numbers. The `natsorted()` function acts as a drop-in replacement for Python's built-in `sorted()`.

from natsort import natsorted

unsorted_list = ['file1.txt', 'file10.txt', 'file2.txt', 'file_2.jpeg', 'file_1.png', 'file_10.gif']
sorted_list = natsorted(unsorted_list)

print(sorted_list)
# Expected output: ['file_1.png', 'file1.txt', 'file_2.jpeg', 'file2.txt', 'file_10.gif', 'file10.txt']

view raw JSON →