如何将字符串拆分为python中不包含空格的单词?

时间:2012-02-09 07:28:03

标签: python string list whitespace

我的字符串是:

"This     is a      string"

我想把它变成一个列表:

["This", "is", "a", "string"]

我使用split(" ")方法,但它添加了空格作为列表元素。请帮忙,

最好的问候

3 个答案:

答案 0 :(得分:11)

>>> v="This is a  string"

>>> v.split()
['This', 'is', 'a', 'string']

只需使用split()

答案 1 :(得分:3)

如果您只使用.split()而不是.split(' ')

,则不会将空格添加为元素
>>> "This     is a     string".split()
['This', 'is', 'a', 'string']

答案 2 :(得分:2)

如同the docs所说,不要传递论据。

>>> "This is a string".split()
['This', 'is', 'a', 'string']