-1

I am trying to sort a list of strings:

l = ['img1','img2','img11','img3']

I tried this:

l.sort()
>>>['img1', 'img11', 'img2', 'img3']

but the result is not what I want. how can I sort the list so that i get the results below:

['img1', 'img2', 'img3', 'img11']
M.Pt
  • 3
  • 1

1 Answers1

1

You can use the key feature in the sorted method. Here re is used to get the integer from the string.

In [1]: import re

In [2]: sorted(l, key=lambda x: int(re.search(r'\d+', x).group()))
Out[2]: ['img1', 'img2', 'img3', 'img11']
Rahul K P
  • 15,740
  • 4
  • 35
  • 52