How to Sort Strings in Python by Whether They Contain Digits or Not?

Estimated read time 2 min read

To sort strings in Python based on whether they contain digits or not, you can use the built-in sorted() function with a custom sorting function that checks whether each string contains digits or not.

Here’s an example of how to sort a list of strings based on whether they contain digits or not:

my_list = ['apple1', 'cherry', 'banana2', 'kiwi', 'orange3']
sorted_list = sorted(my_list, key=lambda x: (not x.isdigit(), x))

print(sorted_list)  # Output: ['cherry', 'kiwi', 'orange3', 'apple1', 'banana2']

In this example, we define a custom sorting function using a lambda function that checks whether each string contains digits using the isdigit() method. The lambda function returns a tuple with two values: the first value is True if the string does not contain digits and False otherwise, and the second value is the original string itself. We pass the lambda function as the key argument to the sorted() function, which tells Python to use the tuple of values for sorting.

We then use the sorted() function to sort the list based on the tuples of values. The not operator is used to invert the result of isdigit(), so that strings that do not contain digits are sorted before strings that do contain digits.

Finally, we print the sorted list to verify that it is sorted based on whether the strings contain digits or not.

Note that this approach assumes that you want to sort the strings based on whether they contain digits or not, and that you want to preserve the original order of the strings that have the same property. If you want to sort the strings based on a different criterion (e.g., the length of the strings), you may need to modify the lambda function accordingly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply