Home >Backend Development >Python Tutorial >How Can I Sort Strings with Embedded Numbers Naturally in Python?
Natural Sorting: The Art of Arranging Strings with Embedded Numbers
Sorting strings with numbers can be a tricky task, but it's essential for many applications. In this Q&A, we'll explore a solution that achieves human-like sorting results, allowing you to arrange strings like "something1", "something2", and "something17" in a logical order.
The Challenge:
The given input consists of a list of strings containing numbers. However, the default sort() method fails to arrange them in a way that makes sense to humans. For instance, the following list:
something1 something12 something17 something2 something25 something29
would be sorted as:
something1 something12 something17 something2 something25 something29
The Solution: Natural Keys
The solution lies in using natural keys, a sorting method designed for human readability. Natural keys treat numbers within strings as separate entities while maintaining the overall structure of the string.
Here's a Python implementation using the natural_keys function:
import re def natural_keys(text): return [int(c) if c.isdigit() else c for c in re.split(r'(\d+)', text)]
When applied to the input list, the result would be:
['something1', 'something2', 'something12', 'something17', 'something25', 'something29']
Additional Considerations:
If you need to sort strings with floating-point numbers, you can modify the regex in the natural_keys function to match floats instead of integers.
def natural_keys(text): return [float(c) if c.isdigit() or '.' in c else c for c in re.split(r'[+-]?([0-9]+(?:[.][0-9]*)?|[.][0-9]+)', text)]
This enhancement enables you to sort strings like:
something1 something2 something1.0 something1.25 something1.105
in the following order:
['something1', 'something1.0', 'something1.105', 'something1.25', 'something2']
By embracing the power of natural keys, you can now effortlessly arrange strings with embedded numbers in a human-readable manner, making your data manipulation tasks more efficient and intuitive.
The above is the detailed content of How Can I Sort Strings with Embedded Numbers Naturally in Python?. For more information, please follow other related articles on the PHP Chinese website!