【发布时间】:2014-05-29 14:38:31
【问题描述】:
所以我有一大串由空格和制表符分隔的单词,我想知道如何快速将每个单词附加到列表中。
EX.
x = "hello Why You it from the"
list1 = ['hello', 'why', 'you', 'it','from', 'the']
字符串有不同的制表符和多个空格,我只需要一个快速的解决方案,而不是手动解决问题
【问题讨论】:
所以我有一大串由空格和制表符分隔的单词,我想知道如何快速将每个单词附加到列表中。
EX.
x = "hello Why You it from the"
list1 = ['hello', 'why', 'you', 'it','from', 'the']
字符串有不同的制表符和多个空格,我只需要一个快速的解决方案,而不是手动解决问题
【问题讨论】:
你可以使用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() 呢?
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,则应用不同的拆分算法:连续的空格被视为单个分隔符,如果字符串的开头或结尾不包含空字符串有前导或尾随空格。
sep 是split() 的第一个参数。
【讨论】: