3

Take a collection of these kinds of strings:

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

The two strings foo: and bar: are of the same length so I would like to start sorting from index of position 5 So my output would be...

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

1 Answer 1

7

Use a key function to slice each string; sorting then takes place using the values produced by the key.

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

Demo:

>>> 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() documentation:

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

Sign up to request clarification or add additional context in comments.

2 Comments

What exactly is key referring to? Is it some sort of keyword?
@Ogen key is an optional argument. From the docs: "The optional arguments cmp, key, and reverse have the same meaning as those for the list.sort() method (described in section Mutable Sequence Types). [...] key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly)."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.