Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort multiple strings inside list alphabetically ascending in Python

I’d like to write a function which can return the sorted strings inside a list by alphabetically ascending. Like it should turn

["banana apple", "cat elephant dog"] 

into

["apple banana", "cat dog elephant"].

I tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def apply_to_list(string_list):
   new = []
   for i in [0,len(string_list)-1]:
    data = sorted(string_list[i])
    new = data.append
    print(new)
    return new

It turned out to be wrong.
I know how to sort if the list is simple, I can do:

def sort_words(string):
    words = [word.lower() for word in string.split()]
    words.sort()
    for word in words:
    print(word)
    return 

However, when it comes to several strings inside each of the attribute of a list, my approach failed.
Can anyone help?

>Solution :

words = ["banana apple", "cat elephant dog"] 

s = [' '.join(sorted(word.split(' '))) for word in words]
print(s)

#['apple banana', 'cat dog elephant']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading