簡體   English   中英

使用python在多個空格上拆分String

[英]Split String on the multiple spaces using python

我想在多個空格上分割字符串,但不在單個空格上。

我已經嘗試過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']

您可以創建一個匹配2個或更多空格的正則表達式,並使用re.split()分割匹配:

import re

s='hi i am    kaveer'   
re.split(r'\s{2,}', s)

結果

['hi i am', 'kaveer']

你不需要導入任何東西,擺脫正則regexp 享受真正的蟒蛇。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM