简体   繁体   English

在找到“,”和 integer 后拆分字符串

[英]split a string after it finds a "," and an integer

For example consider a string:例如考虑一个字符串:

str1 = '1=apple, 2=orange, mango, 3=grape'
#split string by ,
chunks = str1.split(', ')

if i run the code it gives me an output: '1=apple', '2=orange', 'mango', '3=grape'如果我运行代码,它会给我一个 output: '1=apple', '2=orange', 'mango', '3=grape'

but I want my output to be: '1=apple', '2=orange, mango', '3=grape'但我希望我的 output 为:'1=apple', '2=orange, mango', '3=grape'

With the regex module you can model this exactly with a positive lookahead.使用正则表达式模块,您可以 model 这正是具有积极的前瞻性。 This says, split on aa comma and space that is followed by a number:这就是说,用逗号和空格分隔,后跟一个数字:

import re

str1 = '1=apple, 2=orange, mango, 3=grape'

re.split(r', (?=\d)', str1)
# ['1=apple', '2=orange, mango', '3=grape']

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

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