Python | Split string on Kth Occurrence of Character

Many problems of split has been dealt with in past, but sometimes, one can also encounter this problem in which we need to split the string on the Kth occurrence of 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Split string on Kth Occurrence of Character
# Using split() + join()
  
# initializing string 
test_str = "Geeks_for_Geeks_is_best"
  
# split char 
splt_char = "_"
  
# initializing K 
K = 3
  
# printing original string 
print("The original string is : " + str(test_str))
  
# Using split() + join()
# Split string on Kth Occurrence of Character
temp = test_str.split(splt_char)
res = splt_char.join(temp[:K]), splt_char.join(temp[K:])
  
# printing result 
print("Is list after Kth split is : " + str(list(res)))

chevron_right


Output :

The original string is : Geeks_for_Geeks_is_best
Is list after Kth split is : ['Geeks_for_Geeks', 'is_best']

 

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Split string on Kth Occurrence of Character
# Using regex
import re
  
# initializing string 
test_str = "Geeks_for_Geeks_is_best"
  
# split char 
splt_char = "_"
  
# initializing K 
K = 3
  
# printing original string 
print("The original string is : " + str(test_str))
  
# Using regex
# Split string on Kth Occurrence of Character
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(" ")
  
# printing result 
print("Is list after Kth split is : " + str(res))

chevron_right


Output :

The original string is : Geeks_for_Geeks_is_best
Is list after Kth split is : ['Geeks_for_Geeks', 'is_best']


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.