Categories
Python Answers

How to correctly sort a string with a number inside with Python?

Spread the love

Sometimes, we want to correctly sort a string with a number inside with Python.

In this article, we’ll look at how to correctly sort a string with a number inside with Python.

How to correctly sort a string with a number inside with Python?

To correctly sort a string with a number inside with Python, we can create our own function to return the natural keys to sort by.

For instance, we write

import re


def atoi(text):
    return int(text) if text.isdigit() else text


def natural_keys(text):
    return [atoi(c) for c in re.split(r"(\d )", text)]


alist = [
    "something1",
    "something12",
    "something17",
    "something2",
    "something25",
    "something29",
]

alist.sort(key=natural_keys)
print(alist)

to create the atoi function that return the text convert to an int if text is all digits.

Otherwise, we return text.

Then we define the natural_keys function to return the natural keys by returning a list that has the values returned by atoi after splitting the text value by a digit.

Next, we call alist.sort with the key argument set to naturali_keys to sort alist in place by the natural keys.

Conclusion

To correctly sort a string with a number inside with Python, we can create our own function to return the natural keys to sort by.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *