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

使用python仅在多个空格上拆分字符串,python,string,split,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 r

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

我的尝试

>>> _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']
对于如何达到理想的结果有什么建议吗?谢谢。

采用单独的论点。只需将“”传递给它:

给你的答案一个双空格作为引数

>>> _str='The lorry ran  into the mad man  before turning over'
>>> _str.split("  ")
['The lorry ran', 'into the mad man', 'before turning over']
>>> 
split可以使用用于拆分的参数:

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

str.split[sep[,maxslit]]

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']).
使用re模块:


由于需要在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']

是否只有2个空间或任何数量大于1的空间?Hi@Sukritkalla,2个或更多空间。谢谢。我添加了一个答案,该答案将在大于2的任何空间上拆分。
>>> 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']
>>> 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']