简体   繁体   English

Python —拆分具有多个相同定界符的字符串

[英]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. 真正的问题是名称可以是任意长度,但是,我认为可以使用re在一定数量的空格字符后分割字符串(例如至少4个,因为可能总是至少有4个空格)在任何名称的末尾与“ Contact phone开头之间),但使用正则表达式的效果不佳。 If someone could please provide a possible solution (and explanation so I can learn), that would be thoroughly appreciated. 如果有人可以提供可能的解决方案(并提供解释,以便我学习),将不胜感激。

You can use re.split : 您可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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