Sam Houghton Sam Houghton - 1 year ago 87
Python Question

How to turn a string with spaces into a list before alphabetically sorting the list in Python

I have a string which has spaces in it in between words eg:


fish dog house apple


I want to turn it into a list


['fish', 'dog', 'house', 'apple']


And finally sort that list alphabetically


['apple', 'dog', 'fish', 'house']

Answer Source

use sorted() to sort

>>> data = 'fish dog house apple'
>>> sorted(data.split())
>>> ['apple', 'dog', 'fish', 'house']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download