2014-04-02 36 views
0

我的目標是僅在雙空格上分割字符串。請參閱下面的示例字符串以及使用常規拆分函數的嘗試。僅使用python分割多個空格上的字符串

我嘗試

>>> _str='The lorry ran into the mad man before turning over' 
>>> _str.split() 
['The', 'lorry', 'ran', 'into', 'the', 'mad', 'man', 'before', 'turning', 'over'] 

理想的結果:

['the lorry ran', 'into the mad man', 'before turning over'] 

如何在理想的結果得出任何建議?謝謝。

+0

它只有2個空格或大於1的任意數量的空格嗎? –

+0

Hi @SukritKalra,2個或更多的空間。謝謝。 – Tiger1

+0

我添加了一個答案,它可以在任何大於2的空格上分割。 –

回答

2

split可以使用其用於拆分參數:

>>> _str='The lorry ran into the mad man before turning over' 
>>> _str.split(' ') 
['The lorry ran', 'into the mad man', 'before turning over'] 

doc

str.split([SEP [,maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. 
If maxsplit is given, at most maxsplit splits are 
done (thus, the list will have at most maxsplit+1 elements). 

If sep is given, consecutive delimiters are not grouped together and are deemed 
to delimit empty strings (for example, 
'1,,2'.split(',') returns ['1', '', '2']). The sep argument may 
consist of multiple characters (for example, '1<>2<>3'.split('<>') 
returns ['1', '2', '3']). 
2

split需要分隔符參數。只是通過' '它:

>>> _str='The lorry ran into the mad man before turning over' 
>>> _str.split(' ') 
['The lorry ran', 'into the mad man', 'before turning over'] 
>>> 
2

給你split()雙空間作爲一個參數。

>>> _str='The lorry ran into the mad man before turning over' 
>>> _str.split(" ") 
['The lorry ran', 'into the mad man', 'before turning over'] 
>>> 
1

使用re模塊:

>>> import re 
>>> example = 'The lorry ran into the mad man before turning over' 
>>> re.split(r'\s{2}', example) 
['The lorry ran', 'into the mad man', 'before turning over'] 
1

,因爲你需要分割的2米或更多的空間,你可以做。

>>> import re 
>>> _str = 'The lorry ran into the mad man before turning over' 
>>> re.split("\s{2,}", _str) 
['The lorry ran', 'into the mad man', 'before turning over'] 
>>> _str = 'The lorry ran  into the mad man  before turning over' 
>>> re.split("\s{2,}", _str) 
['The lorry ran', 'into the mad man', 'before turning over']