【问题标题】:How to get every word out of a string? [duplicate]如何从字符串中取出每个单词? [复制]
【发布时间】:2019-03-26 00:18:55
【问题描述】:

我正在尝试解决一个问题,即我需要获取句子中的每个单词并按字母顺序对其进行排序。在这件事上我真的很感激一些帮助,因为我不太清楚如何将每个单词分别放在一个列表中,这样我就可以对其进行排序。谢谢你的时间! 我曾尝试使用 for 循环来搜索每个空格,但似乎没有成功,因为我不太清楚如何将单词本身取出。

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

【问题讨论】:

  • 提示splitsort
  • 使用split():words = text.split(' ')

标签: python


【解决方案1】:

您需要采取 2 个步骤:

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

代码

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

【讨论】:

    【解决方案2】:

    像这样简单地使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-23
      • 2017-08-08
      • 1970-01-01
      • 2021-06-21
      • 2010-11-12
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      相关资源
      最近更新 更多