- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
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.
- Related Articles
- Python â€“ Sort given list of strings by part the numeric part of string
- Python â€“ Sort by Rear Character in Strings List
- Python How to sort a list of strings
- Python Get the numeric prefix of given string
- Python program to Sort a List of Strings by the Number of Unique Characters
- How to sort a list of strings in Python?
- Python â€“ Sort String list by K character frequency
- Python â€“ Sort Strings by Case difference
- Python Categorize the given list by string size
- Program to count number of ways we can make a list of values by splitting numeric string in Python
- Sort list of tuples by specific ordering in Python
- Check if given string can be formed by concatenating string elements of list in Python
- Python program to Sort Strings by Punctuation count
- Python program to sort strings by substring range
- Python - Find all the strings that are substrings to the given list of strings