Change language

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

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method