使用python仅在多个空格上拆分字符串

时间:2014-04-02 13:16:42

标签: python string split

我的目标是仅将字符串拆分为双白空格。请参阅下面的示例字符串和使用常规拆分函数的尝试。

我的尝试

>>> _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']

有关如何达到理想结果的任何建议?感谢。

5 个答案:

答案 0 :(得分: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 :(得分: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 :(得分: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']).

答案 3 :(得分: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']

答案 4 :(得分: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']