2012-10-23 85 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(" ")]) 

轉換大的空間成單個空間