Open In App

Python | Split CamelCase string to individual strings

Improve
Improve
Like Article
Like
Save
Share
Report

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


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


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


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

Method #5: Using filter(), map(), and a lambda function:

This code defines a function camel_case_split() that takes in a string s and splits it into individual words.

The function first uses map() and a lambda function to add an underscore before each uppercase letter in the string. The modified string is stored in a list called modified_string.

Next, the function uses join() to join the elements in modified_string into a single string, with the underscores serving as delimiters. The resulting string is then split at the underscores using split(), and the resulting list is stored in split_string.

Finally, the function uses filter() and a lambda function to remove any empty strings from split_string, and then returns the resulting list.

The function is then tested on two example strings: “GeeksForGeeks” and “ThisIsInCamelCase”. When the function is called on these strings, it will return a list of the individual words in each string.

Python3




def camel_case_split(s):
    # use map to add an underscore before each uppercase letter
    modified_string = list(map(lambda x: '_' + x if x.isupper() else x, s))
    # join the modified string and split it at the underscores
    split_string = ''.join(modified_string).split('_')
    # remove any empty strings from the list
    split_string = list(filter(lambda x: x != '', split_string))
    return split_string
 
# test the function
str1 = "GeeksForGeeks"
print(camel_case_split(str1))
str2 = "ThisIsInCamelCase"
print(camel_case_split(str2))
#This code is contributed by Edula Vinay Kumar Reddy


Output

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

Time complexity: O(n), where n is the length of the string.

Auxiliary Space: O(n), since new lists are created to store the uppercase letters and the modified string.

Approach#6: using enumerate

In this approach, we use string slicing to split the input string. We iterate over the input string and split it at every uppercase character, except for the first character.

Algorithm

  • Initialize an empty list to store the split strings.
  • Initialize a variable start to 0.
  • For each character c in the input string starting from the second character:
    • If c is uppercase, append the substring from start to i to the list and update start to i.
  • Append the substring from start to the end of the string to the list.
  • Return the list of split strings.

Python3




def camel_case_split(s):
    result = []
    start = 0
    for i, c in enumerate(s[1:], 1):
        if c.isupper():
            result.append(s[start:i])
            start = i
    result.append(s[start:])
    return result
 
 
# test the function
str1 = "GeeksForGeeks"
print(camel_case_split(str1))
str2 = "ThisIsInCamelCase"
print(camel_case_split(str2))


Output

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

Time Complexity: O(n) where n is the length of the input string.
Space Complexity: O(n) where n is the length of the input string.



Last Updated : 24 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads