Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to natural sort in Python

📅 2015-Jan-23 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ natsort, natural sort, python ⬩ 📚 Archive

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


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧