python – 将一串单词的字符串转换为一个单独分隔所有单词的列表

所以我有一个由空格和制表符分隔的大量单词,并且想知道我可以做些什么来快速将每个单词附加到列表中.

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']
>>>
点赞