
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 part the numeric part of string
When it is required to sort a given list of strings based on a numeric part of the string, a method is defined that uses the regular expressions, the ‘map’ method and the ‘list’ method to display the result.
Example
Below is a demonstration of the same −
import re print("The regular expression package has been imported successfully.") def my_digit_sort(my_list): return list(map(int, re.findall(r'\d+', my_list)))[0] my_list = ["pyt23hon", "fu30n", "lea14rn", 'co00l', 'ob8uje3345t'] print("The list is : " ) print(my_list) my_list.sort(key=my_digit_sort) print("The list has been sorted based on the pre-defined method..") print("The resultant list is : ") print(my_list)
Output
The regular expression package has been imported successfully. The list is : ['pyt23hon', 'fu30n', 'lea14rn', 'co00l', 'ob8uje3345t'] The list has been sorted based on the pre-defined method.. The resultant list is : ['co00l', 'ob8uje3345t', 'lea14rn', 'pyt23hon', 'fu30n']
Explanation
The required packages are imported into the environment.
A method named 'my_digit_sort' is defined and it takes a list as a paramater.
It uses the regular expression and the 'findall' method of the 're' package to find the digits present inside the words.
This is mapped to all elements in the list.
This is converted into a list and is returned as output.
Outside the method, a list of strings that contains integers is defined and displayed on the console.
This list is sorted based on the pre-defined method.
This output is displayed on the console.
- Related Questions & Answers
- Python – Sort given list of strings by numeric part of string
- Python – Substitute prefix part of List
- Python – Sort by Rear Character in Strings List
- Sort a MySQL table column value by part of its value?
- Split the left part of a string by a separator string in MySQL?
- Python – Sort Strings by Case difference
- Python – Sort String list by K character frequency
- PHP – How to get the selected part of a string using mb_substr()?
- How to order by certain part of a string in MySQL?
- Fetch middle part of a string surrounded by slash in MySQL
- PHP – How to cut out part of a string using iconv_substr()?
- Python Get the numeric prefix of given string
- MySQL query to change a string by displaying only the part of string after underscore?
- Replace part of string in MySQL table column?
- Python program to Sort a List of Strings by the Number of Unique Characters