How can I split by 1 or more occurrences of a delimiter in Python?

前端 未结 6 1027
旧时难觅i
旧时难觅i 2020-12-05 09:56

I have a formatted string from a log file, which looks like:

>>> a=\"test                            result\"

That is, the test an

相关标签:
6条回答
  • 2020-12-05 10:06

    Just do not give any delimeter?

    >>> a="test                            result"
    >>> a.split()
    ['test', 'result']
    
    0 讨论(0)
  • 2020-12-05 10:09

    If you want to split by 1 or more occurrences of a delimiter and don't want to just count on the default split() with no parameters happening to match your use case, you can use regex to match the delimiter. The following will use one or more occurrences of . as the delimiter:

    s = 'a.b....c......d.ef...g'
    sp = re.compile('\.+').split(s)
    print(sp)
    

    which gives:

    ['a', 'b', 'c', 'd', 'ef', 'g']
    
    0 讨论(0)
  • 2020-12-05 10:11

    Any problem with simple a.split()?

    0 讨论(0)
  • 2020-12-05 10:23
    >>> import re
    >>> a="test                            result"
    >>> re.split(" +",a)
    ['test', 'result']
    
    >>> a.split()
    ['test', 'result']
    
    0 讨论(0)
  • 2020-12-05 10:25

    Just this should work:

    a.split()
    

    Example:

    >>> 'a      b'.split(' ')
    ['a', '', '', '', '', '', 'b']
    >>> 'a      b'.split()
    ['a', 'b']
    

    From the documentation:

    If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

    0 讨论(0)
  • 2020-12-05 10:25

    Just adding one more way, more useful in cases where delimiter is different from space, and s.split() will not work.

    like str = "Python,is,,more,,,,,flexible".

    In [27]: s = "Python,is,,more,,,,,flexible"
    
    In [28]: str_list = list(filter(lambda x: len(x) > 0, s.split(",")))
    
    In [29]: str_list
    Out[29]: ['Python', 'is', 'more', 'flexible']
    
    0 讨论(0)
提交回复
热议问题