How to natural sort in Python

A lot of sources generate filenames or strings numbered naturally: bat_1, ... bat_9, bat_10. The sort in Python is lexicographic and does not result in a natural ordering of such strings.

The natsort Python package can be used to sort such strings naturally.

Installation for Python 3.x:

$ sudo pip3 install natsort

Usage is simple:

import natsort
out_list = natsort.natsorted(fname_list)

Other uses of this package can be found here.

Tried with: natsort 3.5.2, Python 3.4 and Ubuntu 14.04


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.