Reputation: 61
I want to split the string on multiple spaces but not on single space.
I have tried string.split() but it splits on every single space
here is my code
string='hi i am kaveer and i am a student'
string.split()
i expected the result
['hi i am','kaveer','and i am a','student']
but actual result is
['hi','i','am','kaveer','and','i','am','a','student']
Upvotes: 4
Views: 2430
Reputation: 1152
You don't need to import anything, get rid of regexp
. Enjoy real python.
>>> string='hi i am kaveer and i am a student'
>>> new_list = list(map(lambda strings: strings.strip(), string.split(' ')))
['hi i am', '', 'kaveer', 'and i am a', 'student']
# remove empty string from list.
>>> list(filter(None, new_list))
['hi i am', 'kaveer', 'and i am a', 'student']
# Or you could combine it all of these on one line,
# Of course you could loose readability.
>> list(filter(None, list(map(lambda strings: strings.strip(), string.split(' ')))))
Upvotes: 0
Reputation: 92461
You can make a regular expression that matches 2 or more spaces and use re.split()
to split on the match:
import re
s='hi i am kaveer'
re.split(r'\s{2,}', s)
result
['hi i am', 'kaveer']
Upvotes: 8