Python如何拆分含有多种分隔符的字符串

Jackey Python 1,647 次浏览 , 没有评论
# 如何拆分含有多种分隔符的字符串

import os

# 单一分隔符
x = os.popen('ps aux').read().splitlines()
s = x[-1]
# s.split()
# 如果是空格、制表符等空白分隔,可以不用传参
print(s.split())

s = 'ab;cd|efg|hi,jkl|mn\topq;rst,uvw\txyz'
res = s.split(';')
print(res)

# res = map(lambda x: x.split('|'), res)
# print(list(res))
t = []
list(map(lambda x: t.extend(x.split('|')), res))
print(t)
res = t
t = []
list(map(lambda x: t.extend(x.split(',')), res))
print(t)
res = t
t = []
list(map(lambda x: t.extend(x.split('\t')), res))
print(t)


def mySplit(s, ds):
    res = [s]
    for d in ds:
        t = []
        list(map(lambda x: t.extend(x.split(d)), res))
        res = t
    # 过滤空字符串
    return [x for x in res if x]


s = 'ab;cd|efg|hi,,jkl|mn\topq;rst,uvw\txyz'
res = mySplit(s, ';,|\t')
print(res)

# 第二种方法, 使用正则表达式
import re
res = re.split(r'[,;\t|]+', s)
print(res)

# 单一分隔用s.split()速度更快,但是不能使用多个分隔符分隔

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go