-8

I am trying to solve a problem where I need to get every word in the sentence and sort it alphabetically. I would really appreciate some help in the matter, as I don't quite have a clue about how to get every word separately inside a list so i could sort it. Thanks for your time! I have tried using a for loop to search for every space but it didn't seem to work out as I didn't have quite enough of an idea how to get the word itself out.

    if action = "sort"
        for word in text:
            if word == " ":
                pass
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
ron zamir
  • 23
  • 6

2 Answers2

0

Simply use the split method like so.

s = "your string"
lst = s.split() # would return lst = ["your", "string"]. split could take a separator parameter. s.split(“r”) -> ["you", " st", "ing"]

lst.sort() # this would sort your words
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
marc
  • 914
  • 6
  • 18
0

You have 2 steps to take:

  1. Convert the string into a list of words
  2. Sort the list from the previous step

Code

sentence = 'split this sentence'
words_list = sentence.split(' ')
sorted_word_list = sorted(words_list)
balderman
  • 22,927
  • 7
  • 34
  • 52