Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python | Split CamelCase string to individual strings

  • Last Updated : 20 May, 2019

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

Examples:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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.




# 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 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 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']



My Personal Notes arrow_drop_up
Recommended Articles
Page :