Home > Net >  splitting a string with multiple delimiters doesn't work
splitting a string with multiple delimiters doesn't work

Time:10-06

I'm trying to split a string suing multiple delimiters. Somehow it just doesn't work, it only works if I use each delimiter separately. What am I doing wrong?

string = '\r\n\r\n \r\n\r\nfirst_col: col1 \r\n\r\nsecond_col: col2 \r\n\r\nthird_col: col3 \r\n\r\nfourth_col: col4 \r\n\r\nfith_col: col5\r\n'
splitter = "\r\n\r\n | \r\n\r\n| "
string.split(splitter)

CodePudding user response:

Use re.split() to split the string according to a regex pattern:

import re

string = '\r\n\r\n \r\n\r\nfirst_col: col1 \r\n\r\nsecond_col: col2 \r\n\r\nthird_col: col3 \r\n\r\nfourth_col: col4 \r\n\r\nfith_col: col5\r\n'
splitter = "\r\n\r\n | \r\n\r\n| "

new_string = re.split(splitter, string)
  • Related