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'
but I want my output to be: '1=apple', '2=orange, mango', '3=grape'
With the regex module you can model this exactly with a positive lookahead. 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']
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.