Python | Split CamelCase string to individual strings
Last Updated :
24 Mar, 2023
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.
Similar Reads
Splitting String to List of Characters - Python We are given a string, and our task is to split it into a list where each element is an individual character. For example, if the input string is "hello", the output should be ['h', 'e', 'l', 'l', 'o']. Let's discuss various ways to do this in Python.Using list()The simplest way to split a string in
2 min read
Splitting String to List of Characters - Python The task of splitting a string into a list of characters in Python involves breaking down a string into its individual components, where each character becomes an element in a list. For example, given the string s = "GeeksforGeeks", the task is to split the string, resulting in a list like this: ['G
3 min read
Python - Convert Snake Case String to Camel Case Converting a string from snake case to camel case involves changing the format from words separated by underscores to a single string where the first word is lowercase and subsequent words start with uppercase letters. Using split()This method converts a snake case string into camel case by splittin
3 min read
Python program to split a string by the given list of strings Given a list of strings. The task is to split the string by the given list of strings. Input : test_str = 'geekforgeeksbestforgeeks', sub_list = ["best"] Output : ['geekforgeeks', 'best', 'forgeeks'] Explanation : "best" is extracted as different list element. Input : test_str = 'geekforgeeksbestfor
4 min read
Python | Exceptional Split in String Sometimes, while working with Strings, we may need to perform the split operation. The straightforward split is easy. But sometimes, we may have a problem in which we need to perform split on certain characters but have exceptions. This discusses split on comma, with the exception that comma should
4 min read
Python program to convert camel case string to snake case Camel case is a writing style in which multiple words are concatenated into a single string, Snake case is another writing style where words are separated by underscores (_) and all letters are lowercase. We are going to cover how to convert camel case into snake case.Using Regular Expressions (re.s
3 min read