Python | Split string on Kth Occurrence of Character
Last Updated :
28 Apr, 2023
Many problems of the split have been dealt with in the past, but sometimes, one can also encounter this problem in which we need to split the string on the Kth occurrence of a character. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using split() + join()
The split and join method can perform this particular task. In this, we split the string on basis of character and according to K, we perform a rejoin using the nested join method.
Python3
test_str = "Geeks_for_Geeks_is_best"
splt_char = "_"
K = 3
print ( "The original string is : " + str (test_str))
temp = test_str.split(splt_char)
res = splt_char.join(temp[:K]), splt_char.join(temp[K:])
print ( "Is list after Kth split is : " + str ( list (res)))
|
Output
The original string is : Geeks_for_Geeks_is_best
Is list after Kth split is : ['Geeks_for_Geeks', 'is_best']
Time complexity: O(n), where n is the length of the input string test_str.
Auxiliary space: O(n), where n is the length of the input string test_str.
Method #2: Using regex
This problem can also be solved using the regex to perform this particular task. Along with slicing, the finditer method of regex library can help to achieve this particular task.
Python3
import re
test_str = "Geeks_for_Geeks_is_best"
splt_char = "_"
K = 3
print ( "The original string is : " + str (test_str))
temp = [x.start() for x in re.finditer(splt_char, test_str)]
res1 = test_str[ 0 :temp[K - 1 ]]
res2 = test_str[temp[K - 1 ] + 1 :]
res = (res1 + " " + res2).split( " " )
print ( "Is list after Kth split is : " + str (res))
|
Output
The original string is : Geeks_for_Geeks_is_best
Is list after Kth split is : ['Geeks_for_Geeks', 'is_best']
Time complexity: O(n), where n is the length of the input string test_str.
Auxiliary space: O(n), where n is the length of the input string test_str.
Method #3: Using maxsplit from split
You can use the split itself to get the kth number the second parameter of the method split, that is the max split, then you have your string.
Python3
test_str = "Geeks for geeks"
K = 1
new_str, rest = test_str.split( " " , K)
new_str_list = test_str.split( " " , K)
print (new_str)
print (rest)
print (f 'list: {new_str_list}' )
|
Output
Geeks
for geeks
list: ['Geeks', 'for geeks']
Time Complexity: O(n) where n is the number of elements in the string list. The maxsplit from split is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the test str.
Method 4: using the find() function
This method finds the index of the Kth occurrence of the space character ” ” using a loop and the find() function. If the Kth occurrence is not found, then the entire string is considered as new_str, and rest is an empty string.
- Initialize the input string test_str as “Geeks for geeks” and the integer K as 1, representing the kth occurrence of the space character ” ” to split the string.
- Initialize a variable idx to -1. This variable will be used to keep track of the index of the kth occurrence of the space character.
- Start a for loop that will iterate K times, where K is the kth occurrence we want to find.
- In each iteration of the loop, find the index of the next occurrence of the space character ” ” using the find() function. The find() function searches for the first occurrence of the specified substring starting from the specified index idx + 1.
- Update the idx variable to the index of the last found occurrence.
- After the loop, check if the idx variable was updated to a valid index or not. If idx is still -1, it means that the kth occurrence of the space character was not found in the input string. In this case, assign the entire input string to the variable new_str and an empty string to rest.
- Otherwise, if idx is a valid index, then the substring up to the kth occurrence of the space character will be assigned to new_str, and the substring after the kth occurrence will be assigned to rest.
- Finally, print the values of new_str and rest using the print() function.
Example:
Python3
test_str = "Geeks for geeks"
K = 1
idx = - 1
for i in range (K):
idx = test_str.find( " " , idx + 1 )
if idx = = - 1 :
new_str = test_str
rest = ""
else :
new_str = test_str[:idx]
rest = test_str[idx + 1 :]
print (new_str)
print (rest)
|
Time complexity: O(K * n), where n is the length of the input string.
Auxiliary space: O(1), as we only use a constant amount of extra space to store variables idx, new_str, and rest
Method #6 using the re.split() function:
- We use the re.split() function along with a regular expression pattern \s to split the string at white spaces.
- We set the maxsplit argument to K to split the string at the kth occurrence.
- We then join the first part using a space and extract the rest of the string.
- The new_str_list variable contains the split parts of the string as a list.
Python3
import re
test_str = "Geeks for geeks"
K = 1
print ( "The original string is : " + test_str)
new_str_list = re.split(r '\s' , test_str, maxsplit = K)
new_str = ' ' .join(new_str_list[:K])
rest = ' ' .join(new_str_list[K:])
print (new_str)
print (rest)
print (f 'list: {new_str_list}' )
|
Output
The original string is : Geeks for geeks
Geeks
for geeks
list: ['Geeks', 'for geeks']
Time complexity: O(N), where n is the length of the input string.
Auxiliary space: O(M), where m is the number of parts obtained after splitting the string at the kth occurrence.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...