Python_ How do I split a string with multiple delimiters?

Source: Internet
Author: User

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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.