Split on more than one space?

后端 未结 2 1946
执念已碎
执念已碎 2020-12-21 11:31

I have a program that needs to split lines that are of the format:

IDNumber      Firstname Lastname    GPA      Credits

but I want to keep

相关标签:
2条回答
  • 2020-12-21 12:23

    If you want to split by any whitespace, you can use str.split:

    mystr.split()
    
    # ['IDNumber', 'Firstname', 'Lastname', 'GPA', 'Credits']
    

    For two or more spaces:

    list(filter(None, mystr.split('  ')))
    
    # ['IDNumber', 'Firstname Lastname', 'GPA', 'Credits']
    
    0 讨论(0)
  • 2020-12-21 12:29

    Use regex to split on two or more spaces:

    >>> re.split(r" {2,}", s)
    ['IDNumber', 'Firstname Lastname', 'GPA', 'Credits']
    

    If you want to split on two or more white-space characters generally, then use:

    re.split(r"\s{2,}", s)
    

    e.g.:

    >>> s = "hello, world\t\tgoodbye cruel world"
    >>> print(s)
    hello, world        goodbye cruel world
    >>> re.split(r"\s{2,}", s)
    ['hello, world', 'goodbye cruel world']
    
    0 讨论(0)
提交回复
热议问题