Mario Santoro
Mario Santoro

Reputation: 31

How can I split a string when a character changes from uppercase to lowercase in Python?

I need to split a string in sequences of uppercase and lowercase characters. For example, the string "ABcdEFgh" should be converted into ["AB", "cd", "EF", gh"].

I've tried this:

string1 = "ABcdEFgh"

def split_upp_low(string):
    for n, char in enumerate(string):
        if char.isupper():
            if string[n+1].islower():
                list1 = string.split(char)
    return list1

But the functions returns ['ABcdE', 'gh'] instead of ["AB", "cd", "EF", gh"]. How could I solve this?

Edit: In addition to the solution that schwobaseggl provided, is there any way of doing this without importing libraries?

Upvotes: 2

Views: 171

Answers (2)

user2390182
user2390182

Reputation: 73470

You can use itertools.groupby, your handy util to, well, group stuff:

from itertools import groupby

string1 = 'ABcdEFgh'
list1 = [''.join(g) for _, g in groupby(string1, key=str.islower)]
# ['AB', 'cd', 'EF', 'gh']

For a hand-coded approach, I'd go with a generator function:

def chunks(s):
    chunk = ''
    for char in s:
        if chunk and chunk[-1].islower() != char.islower():
            yield chunk
            chunk = ''
        chunk += char
    if chunk:
        yield chunk

>>> list(chunks(string1))
# ['AB', 'cd', 'EF', 'gh']

Upvotes: 4

Srivatsav Raghu
Srivatsav Raghu

Reputation: 409

Here is a solution without importing any library with basic py implementation:

string1 = "ABcdEFgh"
final = []
def split_upp_low(string1):
    string1 = list(string1)
    string = ''
    check = 0
    for ele in string1:
        if ele.isupper() and check == 0:
            string += ele
        if ele.isupper() and check == 1:
            final.append(string)
            string = ele
            check = 0
        if ele.islower() and check == 1:
            string += ele
        if ele.islower() and check == 0:
            final.append(string)
            string = ele
            check = 1
    final.append(string)
    return final

Upvotes: 1

Related Questions