[英]Splitting a string in python by what follows the split character
我有一個看起來像的字符串,
s = '1 john 2 james 34 baker 45 discover'
我需要一個看起來像的清單,
split_list = ['1 john', '2 james', '34 baker', '45 discover']
我開始使用正則表達式split來執行此操作,但未獲得所需的結果,
import re
s = '1 john 2 james 34 baker 45 discover'
s = re.split('\d+',s)
print s
['', ' john ', ' james ', ' baker ', ' discover']
我猜分割不起作用,因為它不返回分割模式。 任何以pythonic方式執行此操作的線索
您也可以使用非捕獲先行。 (?=\\d+)
確保空格后有一個數字,但不包含在定界符中。
import re
s = '1 john 2 james 34 baker 45 discover'
s = re.split(' (?=\d+)',s)
print s
['1 john', '2 james', '34 baker', '45 discover']
嘗試相反。
s = re.findall('\d+ \w+',s)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.