Case:
Splits a string by delimiter, which contains a different number of delimiters, as follows
s = ' 12;; 7.OSJD;. Jshdjdknx+ '
among them;. + is delimiter
What are the solutions?
Method 1: Use the Str.split () method to process one delimiter at a time
#!/usr/bin/python3def Go_split (S, symbol): result = [s] for i in symbol: median = [] # Normal Method # for X in Result: # Median.extend (X.split (i) # list Parsing # [Median.extend (Y.split (i)) for y in result if y] # Map high-order function, map generates an iterative object for the z in map (lambda x:x.split (i), result): median.extend (z) # More than three methods can solve the problem result = Median # Removes the empty string return [x for x in result if x]if __name__ = = "__main__": # defines the initial string s = ' 12;; 7.OSJD;. jshdjdknx+ ' # defines the delimiter symbol = ';. /+ ' result = Go_split (s, symbol) print (Result)
Method 2: Split all strings at once using the Re.split () method, recommended
#!/usr/bin/python3import Redef go_split (S, symbol): # splicing Regular expression symbol = "[" + Symbol + "]+" # One-time split string res Ult = Re.split (symbol, s) # removes the null character return [x for x in result if x]if __name__ = = "__main__": # defines the initial string s = ' 12;; 7.OSJD;. jshdjdknx+ ' # defines the delimiter symbol = ';. /+ ' result = Go_split (s, symbol) print (Result)
Python_ How do I split a string with multiple delimiters?