我想将字符串拆分为多个空格,而不是单个空格。
我尝试过string.split(),但它会在每个空格处分割
这是我的代码
string='hi i am kaveer and i am a student'
string.split()
我希望得到结果
['hi i am','kaveer','and i am a','student']
但实际结果是
['hi','i','am','kaveer','and','i','am','a','student']
答案 0 :(得分:3)
您可以创建一个匹配2个或更多空格的正则表达式,并使用re.split()
进行匹配:
import re
s='hi i am kaveer'
re.split(r'\s{2,}', s)
结果
['hi i am', 'kaveer']
答案 1 :(得分:0)
您无需导入任何内容,而无需使用regexp
。享受真正的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(' ')))))