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
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]
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
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 :])]
str = "GeeksForGeeks"
print (camel_case_split( str ))
|
Method #3: Using Python regex
Python3
import re
def camel_case_split( str ):
return re.findall(r '[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))' , str )
str = "GeeksForGeeks"
print (camel_case_split( str ))
|
Method #4 : Using isupper(),split(),remove() methods.
Python3
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):
modified_string = list ( map ( lambda x: '_' + x if x.isupper() else x, s))
split_string = ' '.join(modified_string).split(' _')
split_string = list ( filter ( lambda x: x ! = '', split_string))
return split_string
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 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
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 i
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 - Splitting Text and Number in string
Given a string containing both letters and numbers, the task is to separate the text (letters) and the numbers into two separate outputs. For example, if the input is "abc123", the output should be "abc" and "123". Let's discuss various ways in which we can achieve this in Python. Using for loopThis
3 min read
Python | Splitting string list by strings
Sometimes, while working with Python strings, we might have a problem in which we need to perform a split on a string. But we can have a more complex problem of having a front and rear string and need to perform a split on them. This can be multiple pairs for split. Let's discuss certain way to solv
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 | Splitting list on empty string
Sometimes, we may face an issue in which we require to split a list to list of list on the blank character sent as deliminator. This kind of problem can be used to send messages or can be used in cases where it is desired to have list of list of native list. Let's discuss certain ways in which this
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 | Removing Initial word from string
During programming, sometimes, we can have such a problem in which it is required that the first word from the string has to be removed. These kinds of problems are common and one should be aware about the solution to such problems. Let's discuss certain ways in which this problem can be solved. Met
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.
3 min read
Ways to split strings using newline delimiter - Python
The goal is to break down the string wherever a newline character (\n, \r, or \r\n) appears, making it easier to process each line individually. For example, in the string "line1\nline2\rline3\r\nline4", different newline characters are used and we aim to efficiently split this string into separate
2 min read