簡體   English   中英

在每三個空格處分割一個字符串

[英]Split a string on every third space

如何在每三個空格處分割一個字符串? 我想知道python是否具有內置語法,或者是否可以使用列表推導來完成。

"a bb c dd ee f" -> ["a bb c", "dd ee f"]
re.split(r'(.*?\s.*?\s.*?)\s', "a bb c dd ee f")

為了從結果中刪除空字符串:

[x for x in re.split(r'(.*?\s.*?\s.*?)\s', "a bb c dd ee f") if x]

作為更通用的方法,您可以使用函數:

>>> def spliter(s,spl,ind):
...    indx=[i for i,j in enumerate(s) if j==spl][ind-1]
...    return [s[:indx],s[indx+1:]]
... 
>>> s="a bb c dd ee f"
>>> spliter(s,' ',3)
['a bb c', 'dd ee f']

暫無
暫無

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

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