如何从字符串中提取每个单词?

时间:2019-03-24 11:59:33

标签: python

我正在尝试解决一个问题,我需要获取句子中的每个单词并按字母顺序对其进行排序。在此问题上,我将不胜感激,因为我不太了解如何将每个单词分别放入列表中,因此我可以对其进行排序。谢谢你的时间! 我尝试过使用for循环来搜索每个空间,但似乎没有成功,因为我对如何弄清单词本身还没有足够的了解。

    if action = "sort"
        for word in text:
            if word == " ":
                pass

2 个答案:

答案 0 :(得分:0)

像这样简单地使用split方法。

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

答案 1 :(得分:0)

您需要执行2个步骤:

  1. 将字符串转换为单词的列表
  2. 排序上一步中的列表

代码

sentence = 'split this sentence'
words_list = sentence.split(' ')
sorted_word_list = sorted(words_list)