python – Convert string to list sorted in lexicographic order

Question:

How to convert a string consisting of space-separated words into a list and sort the resulting list in lexicographic order?

Given a string of words separated by spaces:

s = 'abc a bCd bC AbC BC BCD bcd ABC'

convert it to a list, with a "space" separator:

a = s.split(' ')

we get:

['abc', 'a', 'bCd', 'bC', 'AbC', 'BC', 'BCD', 'bcd', 'ABC']

now if you do this:

a = a.sort()
print (a)

we won't get anything if so:

b = a.sort()
print (a)

get sorted list

['ABC', 'AbC', 'BC', 'BCD', 'a', 'abc', 'bC', 'bCd', 'bcd']

why is that? is it possible to somehow combine sort() and split() in one line?

Answer:

It's simple:

a = sorted(s.split(' '))

In reverse order:

a = sorted(s.split(' '), reverse=True)
Scroll to Top