Kiwi
Kiwi

Reputation: 13

Python: How to sort strings with regards to their trailing numbers?

What is the best way to sort a list of strings with trailing digits

>>> list = ['mba23m23', 'mba23m124', 'mba23m1', 'mba23m5']
>>> list.sort()
>>> print list
['mba23m1', 'mba23m124', 'mba23m23', 'mba23m5']

is there a way to have them sorted as

['mba23m1', 'mba23m5', 'mba23m23', 'mba23m124']

Upvotes: 1

Views: 229

Answers (3)

YJR
YJR

Reputation: 1202

  1. Create a function to remove trailing digits and return other part of the string. (Lets consider this function as f_remove_trailing_digits(s) )

you can use following function:

   def f_remove_trailing_digits(s):
           return s.rstrip("0123456789")
  1. Then you can sort using this way

    list.sort(key=lambda x:f_remove_trailing_digits(x))

Upvotes: 1

Shayan Sakha
Shayan Sakha

Reputation: 83

you can use natsort library.

from natsort import natsorted # pip install natsort
list = ['mba23m23', 'mba23m124', 'mba23m1', 'mba23m5']

output:

['mba23m1', 'mba23m5', 'mba23m23', 'mba23m124']

Upvotes: 1

Richard Herron
Richard Herron

Reputation: 10102

Use a lambda (anonymous) function and sort()'s key argument:

ls = ['mba23m23', 'mba23m124', 'mba23m1', 'mba23m5']
ls.sort(key=lambda x: int(x.split('m')[-1]))
print(ls)

Yielding:

['mba23m1', 'mba23m5', 'mba23m23', 'mba23m124']

Upvotes: 0

Related Questions