- 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 Get the numeric prefix of given string
- Python How to sort a list of strings
- Python program to Sort a List of Strings by the Number of Unique Characters
- Python – Sort by Rear Character in Strings List
- How to sort a list of strings in Python?
- Python – Sort String list by K character frequency
- Sort list of tuples by specific ordering in Python
- Python Categorize the given list by string size
- Python – Substitute prefix part of List
- Python – Sort Strings by Case difference
- Sort a MySQL table column value by part of its value?
- Check if given string can be formed by concatenating string elements of list in Python
- Ways to sort list of dictionaries by values in Python
- Program to count number of ways we can make a list of values by splitting numeric string in Python