Tiger1
Tiger1

Reputation: 1377

Splitting a string only on multiple white spaces using python

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

Answers (5)

Sukrit Kalra
Sukrit Kalra

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

logc
logc

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

fredtantini
fredtantini

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

msvalkon
msvalkon

Reputation: 12077

Give your split() a double space as an argument.

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

Upvotes: 2

sloth
sloth

Reputation: 101162

split takes a seperator argument. Just pass ' ' to it:

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

Upvotes: 2

Related Questions