简体   繁体   中英

Python — split a string with multiple occurrences of same delimiter

How can I take a string that looks like this

string = 'Contact name: John Doe                     Contact phone: 222-333-4444'

and split the string on both colons? Ideally the output would look like:

['Contact Name', 'John Doe', 'Contact phone','222-333-4444']

The real issue is that the name can be an arbitrary length however, I think it might be possible to use re to split the string after a certain number of space characters (say at least 4, since there will likely always be at least 4 spaces between the end of any name and beginning of Contact phone ) but I'm not that good with regex. If someone could please provide a possible solution (and explanation so I can learn), that would be thoroughly appreciated.

You can use re.split :

import re
s = 'Contact name: John Doe                     Contact phone: 222-333-4444'
new_s = re.split(':\s|\s{2,}', s)

Output:

['Contact name', 'John Doe', 'Contact phone', '222-333-4444']

Regex explanation:

:\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

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