Home > Backend Development > Python Tutorial > How Can I Perform Natural String Sorting in Python?

How Can I Perform Natural String Sorting in Python?

Mary-Kate Olsen
Release: 2024-12-28 14:29:11
Original
328 people have browsed it

How Can I Perform Natural String Sorting in Python?

Natural String Sorting in Python

Natural sorting is an alphabetic sorting algorithm that handles string numbers and versions correctly. For example, it should sort "elm0" before "elm10" even though "10" is considered greater than "0" in mathematical comparison.

Python's native sorted() function does not perform natural sorting by default. To achieve this behavior, you can utilize the natsort library, which implements a natural sorting algorithm.

To use natsort, install it via:

pip install natsort
Copy after login

Then, depending on your requirements, you can either use the sorting function or a sorting key:

Sorting Function:

from natsort import natsorted

names = ['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
natsorted(names)  # ['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
Copy after login

Sorting Key:

from natsort import natsort_keygen

names = ['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
sort_key = natsort_keygen()
names.sort(key=sort_key)  # ['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
Copy after login

Alternatively, you can use natsort's case-insensitive sorting algorithms if desired:

from natsort import ns

natsorted(names, alg=ns.IGNORECASE)  # ['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
Copy after login

The natsort library provides a comprehensive solution for performing natural sorting in Python, handling various input formats and providing options for case-insensitive sorting as well as compatibility with operating system file system browser sorting.

The above is the detailed content of How Can I Perform Natural String Sorting in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template