4
votes

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?

2
Split by 2 spaces? - actually this is a suggestion. But I'd split ti on one space anr rejoin items 1 and 2. - CristiFati
2 or more spaces - PCRevolt
Use regex; re.split on r'\s{2,}' (two or more whitespace characters). - jonrsharpe
What do you expect as a result? - user1767754

2 Answers

8
votes

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

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