拆分字符串

以多种分隔符作为拆分方式

方法一:使用split()

def mySplit(s, ds):
    res = [s]
    for d in ds:
        t = []
        map(lambda x: t.extend(x.split(d)), res)
        res = t
    return res

s = 'ab;cd|ef|hi\tgk,lm'

print(mySplit(s, ';|\t,'))

运行结果,可以看到这种方式在py2是可以的,但是在py3不行

root@iZ947mgy3c5Z:/tmp# python str_split.py
['ab', 'cd', 'ef', 'hi', 'gk', 'lm']
root@iZ947mgy3c5Z:/tmp# python3 str_split.py
[]

在看一个问题,将s修改一下s = 'ab;;cd|ef|hi\tgk,lm'

root@iZ947mgy3c5Z:/tmp# python2 str_split.py
['ab', '', 'cd', 'ef', 'hi', 'gk', 'lm']

这个问题倒还好解决,return时过滤空元素即可,return [i for i in res if i]

root@iZ947mgy3c5Z:/tmp# python2 str_split.py
['ab', 'cd', 'ef', 'hi', 'gk', 'lm']

py3为什么不行我还没有得出结论,不过先看另一种方法

方法二:使用re.split() 对比下来你会感觉什么是天堂

In [15]: import re
In [16]: re.split?
Signature: re.split(pattern, string, maxsplit=0, flags=0)
Docstring:
Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings.
File:      /usr/lib/python2.7/re.py
Type:      function
In [17]: s = 'ab;cd|ef|hi\tgk,lm'
In [18]: re.split('[,;|\t]+', s)
Out[18]: ['ab', 'cd', 'ef', 'hi', 'gk', 'lm']

results matching ""

    No results matching ""