【问题标题】:Turning a string of a bunch of words into a list with all the words separated将一堆单词的字符串变成一个列表,所有单词都分开
【发布时间】:2014-05-29 14:38:31
【问题描述】:

所以我有一大串由空格和制表符分隔的单词,我想知道如何快速将每个单词附加到列表中。

EX.

x = "hello Why You it     from the"
list1 = ['hello', 'why', 'you', 'it','from', 'the']

字符串有不同的制表符和多个空格,我只需要一个快速的解决方案,而不是手动解决问题

【问题讨论】:

    标签: python string split


    【解决方案1】:

    你可以使用str.split:

    >>> x = "hello Why You it from the"
    >>> x.split()
    ['hello', 'Why', 'You', 'it', 'from', 'the']
    >>> x = "hello                    Why You     it from            the"
    >>> x.split()
    ['hello', 'Why', 'You', 'it', 'from', 'the']
    >>>
    

    没有任何参数,该方法默认为空格字符分割。


    我刚刚注意到您的示例列表中的所有字符串都是小写的。如果需要,可以在str.split之前调用str.lower

    >>> x = "hello Why You it from the"
    >>> x.lower().split()
    ['hello', 'why', 'you', 'it', 'from', 'the']
    >>>
    

    【讨论】:

    • x.lower().split() 呢?
    • @arshajii - 哈,我刚刚发布了那个。 :)
    • 不过,如果您发现列表全是小写,我会给您 +1。
    【解决方案2】:

    str.split() 应该这样做:

    >>> x = "hello Why You it from the"
    >>> x.split()
    ['hello', 'Why', 'You', 'it', 'from', 'the']
    

    如果你想要全部小写(正如@iCodez 也指出的那样):

    >>> x.lower().split()
    ['hello', 'why', 'you', 'it', 'from', 'the']
    

    从上面的链接:

    如果sep 未指定或为None,则应用不同的拆分算法:连续的空格被视为单个分隔符,如果字符串的开头或结尾不包含空字符串有前导或尾随空格。

    sepsplit() 的第一个参数。

    【讨论】:

      猜你喜欢
      • 2020-02-05
      • 2019-11-07
      • 1970-01-01
      • 2019-01-11
      • 2013-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多