将一个由一堆单词组成的字符串转换为列表,其中所有单词都被分隔开。

3

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

例如:

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

这个字符串中有制表符和多个单词之间变化的空格,我需要一个快速的解决方案,而不是手动修复问题。

2个回答

5
您可以使用 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
@arshajii - 哈哈,我正想要发表这个呢。 :) - user2555451
我会给你一个+1,因为你发现列表都是小写的。 - arshajii

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() 的第一个参数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接