Reputation: 1377
My goal is to split the string below only on double white spaces. See example string below and an attempt using the regular split function.
My attempt
>>> _str='The lorry ran into the mad man before turning over'
>>> _str.split()
['The', 'lorry', 'ran', 'into', 'the', 'mad', 'man', 'before', 'turning', 'over']
Ideal result:
['the lorry ran', 'into the mad man', 'before turning over']
Any suggestions on how to arrive at the ideal result? thanks.
Upvotes: 0
Views: 114
Reputation: 34531
Since, you need to split on 2 or more spaces, you can do.
>>> 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']
Upvotes: 1
Reputation: 3923
Use the re
module:
>>> 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']
Upvotes: 1
Reputation: 16586
split
can use an argument which is used to split:
>>> _str='The lorry ran into the mad man before turning over'
>>> _str.split(' ')
['The lorry ran', 'into the mad man', 'before turning over']
From the 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']).
Upvotes: 2