[英]Python — split a string with multiple occurrences of same delimiter
我怎樣才能得到一個像這樣的字符串
string = 'Contact name: John Doe Contact phone: 222-333-4444'
並在兩個冒號上拆分字符串? 理想情況下,輸出如下所示:
['Contact Name', 'John Doe', 'Contact phone','222-333-4444']
真正的問題是名稱可以是任意長度,但是,我認為可以使用re
在一定數量的空格字符后分割字符串(例如至少4個,因為可能總是至少有4個空格)在任何名稱的末尾與“ Contact phone
開頭之間),但使用正則表達式的效果不佳。 如果有人可以提供可能的解決方案(並提供解釋,以便我學習),將不勝感激。
您可以使用re.split
:
import re
s = 'Contact name: John Doe Contact phone: 222-333-4444'
new_s = re.split(':\s|\s{2,}', s)
輸出:
['Contact name', 'John Doe', 'Contact phone', '222-333-4444']
正則表達式說明:
:\s => matches an occurrence of ': '
| => evaluated as 'or', attempts to match either the pattern before or after it
\s{2,} => matches two or more whitespace characters
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.