Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String on the multiple spaces using python

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

like image 559
Veer Singh Avatar asked Sep 03 '25 01:09

Veer Singh


1 Answers

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']
like image 150
Mark Avatar answered Sep 04 '25 16:09

Mark