+

Python | Split string by Kth Occurrence of character

Method # 1: Using split () + join ()
The split and join method can accomplish this particular task. In this case, we split the string based on the character and according to K we perform the rejoin using the nested join method.

# Python3 code to demonstrate how it works
# Split line by Kth Character occurence
# Using split () + join ()

 
# initialization string

test_str = " Geeks_for_Geeks_is_best "

  
# split character

splt_char = " _ "

  
# initialization iya K

K = 3

 
# print original line

print ( "The original string is:" + str (test_str))

  
# Using split () + join ()
# Split string by Kth Character occurrence

temp = test_str.split (splt_char )

res = splt_char.join ( temp [: K]), splt_char.join (temp [K:])

 
#result print tat

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

Method # 2: Using Regular Expressions
This problem can also be solved by using regular expressions to accomplish this particular task. Along with slicing, the finditer method of the regex library can help achieve this specific task.

# Python3 code to demonstrate how it works
# Split line by Kth Character occurence
# Using regular expressions

import re

 
# initialization string

test_str = "Geeks_for_Geeks_is_best"

 
# split character

splt_char = "_"

  
# initialization K

K = 3

 
# print original string

print ( "The original string is: " + str (test_str))

 
# Using regular expressions
# Split line by Kth Character occurence

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 result

print ( "Is li st 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`] 
Get Solution for free from DataCamp guru