How to split a string with capital words without preceding whitespace in python

Viewed 95

I'm gonna split a list based on capital letters but the ones that include white space:

list = ['Blue Jackets', 'KingsDucks', 'Senators', 'Oilers', 'Jets', 'Golden Knights', 'Hurricanes', 'RangersIslandersDevils']

and I expect it gives me this:

out =['Blue Jackets', 'Kings','Ducks', 'Senators', 'Oilers', 'Jets',
'Golden Knights', 'Hurricanes',
'Rangers', 'Islanders', 'Devils']

I used re:

for team in list:
    separated=re.findall('[A-Z][^A-Z]*', team)

but it does not seems accurate as it splits for example 'Blue Jackets' into 'Blue' and 'Jackets' which is not right for me

2 Answers

^\s? can match the space, but it's useful to use split

import re
a = ['Blue Jackets', 'KingsDucks', 'Senators', 'Oilers', 'Jets', 'Golden Knights', 'Hurricanes', 'RangersIslandersDevils']

b = []
for i in a:
    # or add other condition or split the string and re.findall again
    if " " in i:
        b.append(i)
        # c = i.split(" ")
        # for j in c:
        #     b.extend(re.findall('[A-Z][^A-Z]*', j))
    else:
        b.extend(re.findall('[A-Z][^A-Z]*', i))

print(b)
>>> ['Blue Jackets', 'Kings', 'Ducks', 'Senators', 'Oilers', 'Jets', 'Golden Knights', 'Hurricanes', 'Rangers', 'Islanders', 'Devils']

For your regular expression, use (assuming names in your list are longer than 1 character(:

separated = re.findall('[A-Z][a-z]+',
Related