Split on more than one space?

匆匆过客 提交于 2021-01-13 09:37:45

问题


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

IDNumber      Firstname Lastname    GPA      Credits

but I want to keep Firstname and Lastname in the same string.

Is there any easy way to do this (other than just splitting into five strings instead of four) and somehow have the split method only split when there is more than one space?


回答1:


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']



回答2:


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']


来源:https://stackoverflow.com/questions/48917121/split-on-more-than-one-space

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!