- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Sort given list of strings by numeric part of string
When it is required to sort given list of strings by numeric part of string, the regular expression and the ‘findall’ method is used.
Below is a demonstration of the same −
import re def my_num_sort(my_str): return list(map(int, re.findall(r'\d+', my_str))) my_list = ["pyth42on", '14is', '32fun', '89to', 'lea78rn'] print("The list is :") print(my_list) my_list.sort(key=my_num_sort) print("The result is :") print(my_list)
The list is : ['pyth42on', '14is', '32fun', '89to', 'lea78rn'] The result is : ['14is', '32fun', 'pyth42on', 'lea78rn', '89to']
The required packages are imported into the environment.
A method is defined that takes a string as a parameter.
It uses the ‘findall’ method to find a match to the specific pattern.
This is converted to a string using the ‘map’ method, and then to a ‘list’.
This is returned as output of the method.
Outside the method, a list of strings is defined and displayed on the console.
The list is sorted based on the key as the previously defined method.
This list is displayed as the output on the console.
- Python – Sort given list of strings by part the numeric part of string
- Python – Sort by Rear Character in Strings List
- Python – Substitute prefix part of List
- Python – Sort Strings by Case difference
- Python – Sort String list by K character frequency
- Python – Strings with all given List characters
- Python Get the numeric prefix of given string
- Python How to sort a list of strings
- Python – Sort a List by Factor count
- Python program to Sort a List of Strings by the Number of Unique Characters
- Python – Sort Matrix by Maximum String Length
- Python Program – Strings with all given List characters
- How to sort a list of strings in Python?
- Python – Sort by Units Digit in a List
- Python – All occurrences of Substring from the list of strings