Home  >  Article  >  Backend Development  >  How to split a string using different delimiters

How to split a string using different delimiters

anonymity
anonymityOriginal
2019-05-25 11:08:422847browse

How to use different delimiters to split a string, split a string according to the delimiter, the character contains different delimiters, as follows

s = '12;;7.osjd ;.jshdjdknx ' where; . is the separator

What are the solutions?

How to split a string using different delimiters

Method 1: Through the str.split() method, process one separator at a time

#!/usr/bin/python3
 
 
def go_split(s, symbol):
    result = [s]
    for i in symbol:
        median = []
        # 普通方法
        # for x in result:
        #     median.extend(x.split(i)
         
        # 列表解析
        # [median.extend(y.split(i)) for y in result if y]
         
        # map高阶函数,map生成可迭代对象
        for z in map(lambda x: x.split(i), result):
            median.extend(z)
     
        # 以上三个方法都可以解决问题
        result = median
         
    # 去除空字符串
    return [x for x in result if x]
 
if __name__ == "__main__":
    # 定义初始字符串
    s = '12;;7.osjd;.jshdjdknx+'
    # 定义分隔符
    symbol = ';./+'
     
    result = go_split(s, symbol)
    print(result)

Method 2: Through the re.split() method, Split all strings at once, recommended

#!/usr/bin/python3
 
import re
 
 
def go_split(s, symbol):
    # 拼接正则表达式
    symbol = "[" + symbol + "]+"
    # 一次性分割字符串
    result = re.split(symbol, s)
    # 去除空字符
    return [x for x in result if x]
 
 
if __name__ == "__main__":
    # 定义初始字符串
    s = '12;;7.osjd;.jshdjdknx+'
    # 定义分隔符
    symbol = ';./+'
     
    result = go_split(s, symbol)
    print(result)

The above is the detailed content of How to split a string using different delimiters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn