Split a string of words with uppercase words

I have a set of names in which the last name is in the capital, and the first and middle names are normal, for example.

OBAMA Barack
DEL MONTE Alfredo

I want to break them into

"OBAMA", "Barack"
"DEL MONTE", "Alfredo"

What is the pythonic way to achieve this?

+3
source share
4 answers
>>> import itertools
>>> [
...    ' '.join(items)
...    for _, items in itertools.groupby('DEL MONTE Alfredo'.split(), str.isupper)
... ]
['DEL MONTE', 'Alfredo']
+8
source
def split_names(names):
    for s in names:
        last_names = []
        name_parts = s.split()
        while name_parts and name_parts[0].isupper():
            last_names.append(name_parts.pop(0))
        yield ' '.join(last_names), ' '.join(name_parts)


names = ["OBAMA Barack", "DEL MONTE Alfredo"]
for last_name, first_name in split_names(names):
    print last_name
    print first_name
    print

prints:

OBAMA
Barack

DEL MONTE
Alfredo
+2
source

You can use a simple regular expression:

import re

a = "DEL MONTE Alfredo"
first, last = re.match(r'([A-Z ]+)\s+(.+)', a).groups()

or loop through a list of words and filter out all capital letters:

first = ' '.join(w for w in a.split() if w.isupper())
last =  ' '.join(w for w in a.split() if not w.isupper())

In my personal opinion, "the most pythonic" === "the simplest."

+2
source

Try the following:

(?![A-Z][a-z])([A-Z ]+) ([A-Z][a-z]+)
0
source

All Articles