Sort from a specific position in a string

Let's take a bunch of lines like this:

"foo: a message"
"bar: d message"
"bar: b message"
"foo: c message"


The two strings foo:

and bar:

are the same length, so I would like to start sorting from the position index 5

So my result would be ...

"foo: a message"
"bar: b message"
"foo: c message"
"bar: d message"



source to share

1 answer

Use a function key

to slice each line; sorting is done using the values ​​generated by the key.

sorted(inputlist, key=lambda s: s[5:])



>>> inputlist = ['foo: a message', 'bar: d message', 'bar: b message', 'foo: c message']
>>> sorted(inputlist, key=lambda s: s[5:])
['foo: a message', 'bar: b message', 'foo: c message', 'bar: d message']


Quoting the sorted()



It indicates a function of one argument, which is used to extract a key from the comparison of each element of the list: key=str.lower

. The default is None

(compare items directly).



All Articles