How to correctly sort a string with a number inside in Python?


This type of sort in which you want to sort on the basis of numbers within string is called natural sort or human sort. For example, if you have the text:

['Hello1','Hello12', 'Hello29', 'Hello2', 'Hello17', 'Hello25']

 Then you want the sorted list to be:

['Hello1', 'Hello2','Hello12', 'Hello17', 'Hello25', 'Hello29']

 and not:

['Hello1','Hello12', 'Hello17', 'Hello2', 'Hello25', 'Hello29']

 To do this we can use the extra parameter that sort() uses. This is a function that is called to calculate the key from the entry in the list. We use regex to extract the number from the string and sort on both text and number. 

 import re
 def atoi(text):
    return int(text) if text.isdigit() elsetext
def natural_keys(text):
    return [ atoi(c) for c in re.split('(\d+)',text) ]
 my_list =['Hello1', 'Hello12', 'Hello29', 'Hello2', 'Hello17', 'Hello25']
 my_list.sort(key=natural_keys)
print my_list

 This will give you the output:

['Hello1','Hello2', 'Hello12', 'Hello17', 'Hello25', 'Hello29']

Updated on: 30-Sep-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements