Python | Split CamelCase string to individual strings

Given a string in 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 to 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

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

 
Method #3 : Using Python regex

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

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


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.