2012-10-23 106 views
2

我试图找到最Python的方式来分割像分割字符串用空格的任意数量

为单个单词“字符串中的一些话”的字符串。 string.split(' ')工作正常,但它返回列表中的一堆空白条目。当然,我可以迭代列表并删除空格,但我想知道是否有更好的方法?

回答

12

只要使用my_str.split()而不是' '


更多,你也可以说明有多少分割,通过指定的第二个参数来执行:

>>> ' 1 2 3 4 '.split(None, 2) 
['1', '2', '3 4 '] 
>>> ' 1 2 3 4 '.split(None, 1) 
['1', '2 3 4 '] 
2

使用string.split()没有参数或re.split(r'\s+', string)代替:

>>> s = 'some words in a string with spaces' 
>>> s.split() 
['some', 'words', 'in', 'a', 'string', 'with', 'spaces'] 
>>> import re; re.split(r'\s+', s) 
['some', 'words', 'in', 'a', 'string', 'with', 'spaces'] 

docs

如果没有指定sep或者是None,则应用不同的分割算法:将连续空白的运行视为单个分隔符,并且如果该字符串具有前导空格或尾随空格,则结果将在开始或结束处不包含空字符串。因此,使用None分隔符将空字符串或仅由空白组成的字符串拆分返回[]

6

如何:

re.split(r'\s+',string) 

\s是短期的任何空白。所以\s+是一个连续的空格。

0
>>> a = "some words in a string" 
>>> a.split(" ") 
['some', 'words', 'in', 'a', 'string'] 

拆分参数不包含在结果中,所以我猜想更多关于您的字符串的东西。否则,它应该工作

,如果你有一个以上的空白只需使用分裂()不带参数

>>> a = "some words in a string  " 
>>> a.split() 
['some', 'words', 'in', 'a', 'string'] 
>>> a.split(" ") 
['some', 'words', 'in', 'a', 'string', '', '', '', '', ''] 

或者它只是通过单一的空格分割

0
text = "".join([w and w+" " for w in text.split(" ")]) 

转换大的空间成单个空间