How to re.split(" ", string) when there are multiple spaces?

Viewed 314
d = ["11:00 PM", "13!00 PM", "11 00 PM"]

for i in d:
    print(re.split(" ", i)

For others it's okay, prints ["11:00", "PM"] and ["13!00", "PM"], but for 11 00 PM it prints ["11", "00", "PM"]. How can I change the regex so it would return ["11 00", "PM"] there too?

1 Answers

For these examples you can use normal text.split() (or rather text.rsplit()) instead of regex

d = ["11:00 PM", "13!00 PM", "11 00 PM"]

for i in d:
    print(i.rsplit(" ", 1))

Result:

['11:00', 'PM']
['13!00', 'PM']
['11 00', 'PM']

EDIT:

if you want to remove "white chars" - space, tab, enter - at both sides then you can use normal text.strip(). Similar rstrip() and lstrip() for right or left side. Or use strip(' ') if you want to remove only spaces and keep tabs and enters.

i = i.strip().rsplit(" ", 1)

d = [" 11:00 PM", "\n 13!00 PM", "11 00 PM"]

for i in d:
    print(i.strip().rsplit(" ", 1))

EDIT: If you want to keep result then you can append to list

d = [" 11:00 PM", "\n 13!00 PM", "11 00 PM"]

results = []    

for i in d:
    results.append(i.strip().rsplit(" ", 1))

print(results)

or you can use list comprehension as @Alexander said in comment

d = [" 11:00 PM", "\n 13!00 PM", "11 00 PM"]

results = [x.strip().rsplit(maxsplit=1) for x in d]

print(results)
Related