4

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

2 Answers 2

8

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']
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, it worked on the previous problem please revisit the question it is becoming more difficult
@VeerSingh this works on your new string too. Have you tried it?
can you tell me how it works or any resource to understand it
@VeerSingh it's a regular expression which is a pattern matcher. \s matches a space, {2,} modifies it to match two or more. If you google regular expression you will find lots of information.
0

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('  ')))))

4 Comments

Is calling 7 functions to split a string really better than a simple regexp? It's also not clear why using python's standard library isn't "real" python.
You have just imported whole re library, which could be simplified just using python's built in functions . Python's re module is based on PCRE.
Your code is great and works, but I'm sorry, real python means readable easy code. Don't see what so bad about a simple regex...
Yeah your code is just great, just simple two lines. I just did without using library. Maybe it may help others.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.