简体   繁体   中英

Splitting a string in python by what follows the split character

I have a string that looks like,

s = '1 john 2 james 34 baker 45 discover'

I need a list that looks like,

split_list = ['1 john', '2 james', '34 baker', '45 discover']

I started to do this by using regex split and did not get the desired result,

import re
s = '1 john 2 james 34 baker 45 discover'
s = re.split('\d+',s)
print s

['', ' john ', ' james ', ' baker ', ' discover']

I guess split does not work since it does not return the splitting pattern. Any clues to do this in a pythonic way

You can also use non capturing lookahead. (?=\\d+) makes sure that there's a number after the space, but it doesn't include as part of the delimiter.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM