Skip to content
Related Articles

Related Articles

Python | Split CamelCase string to individual strings

Improve Article
Save Article
  • Last Updated : 25 Jun, 2022
Improve Article
Save Article

Given a string in a camel-case, write a Python program to split each word in the camel case string into individual strings.

Examples:

Input : "GeeksForGeeks"
Output : ['Geeks', 'For', 'Geeks']

Input : "ThisIsInCamelCase"
Output : ['This', 'Is', 'In', 'Camel', 'Case']

Method #1: Naive Approach A naive or brute-force approach to split CamelCase string into individual strings is to use for loop. First, use an empty list ‘words’ and append the first letter of ‘str’ to it. Now using a for loop, check if the current letter is in lower case or not, if yes append it to the current string, otherwise, if uppercase, begin a new individual string. 

Python3




# Python3 program Split camel case
# string to individual strings
 
def camel_case_split(str):
    words = [[str[0]]]
 
    for c in str[1:]:
        if words[-1][-1].islower() and c.isupper():
            words.append(list(c))
        else:
            words[-1].append(c)
 
    return [''.join(word) for word in words]
     
# Driver code
str = "GeeksForGeeks"
print(camel_case_split(str))

Output:

['Geeks', 'For', 'Geeks']

Method #2: Using enumerate and zip() In this method, we first use Python enumerate to find indices, where the new string begins and save them in ‘start_idx’. Finally using ‘start_idx’ we return each individual string using Python zip

Python3




# Python3 program Split camel case
# string to individual strings
 
import re
 
def camel_case_split(str):
     
    start_idx = [i for i, e in enumerate(str)
                 if e.isupper()] + [len(str)]
 
    start_idx = [0] + start_idx
    return [str[x: y] for x, y in zip(start_idx, start_idx[1:])]
     
     
# Driver code
str = "GeeksForGeeks"
print(camel_case_split(str))

Output:

['', 'Geeks', 'For', 'Geeks']

Method #3: Using Python regex 

Python3




# Python3 program Split camel case
# string to individual strings
import re
 
def camel_case_split(str):
 
    return re.findall(r'[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))', str)
     
# Driver code
str = "GeeksForGeeks"
print(camel_case_split(str))

Output:

['Geeks', 'For', 'Geeks']

Method #4 : Using isupper(),split(),remove() methods.

Python3




# Python3 program Split camel case
# string to individual strings
   
s="ThisIsInCamelCase"
new_string=""
for i in s:
    if(i.isupper()):
        new_string+="*"+i
    else:
        new_string+=i
x=new_string.split("*")
x.remove('')
print(x)

Output

['This', 'Is', 'In', 'Camel', 'Case']

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!