Split string on Kth Occurrence of Character - Python
Last Updated :
18 Jan, 2025
The task is to write Python program to split a given string into two parts at the Kᵗʰ occurrence of a specified character. If the character occurs fewer than K times return the entire string as the first part and an empty string as the second part. For example, in the string "a,b,c,d,e,f", splitting at the 3rd occurrence of "," gives ['a', 'b', 'c', 'd,e,f'].
Using String's split
and join
Using a string's split()
and join()
methods allows for efficient manipulation of text split()
method divides a string into a list of substrings based on a specified delimiter.
Python
s = "hello,world,how,are,you"
k = 2
char = ","
# Splitting the string at the first 2 commas (k=2)
parts = s.split(char, k)
# Joining the first k parts with commas, and then adding the remaining part after the k-th split
res = char.join(parts[:k]) + char + parts[k]
print(res)
Outputhello,world,how,are,you
Explanation:
- String is split at the Kth occurrence of the character.
- Result is reconstructed by joining the first
k
parts and then adding the rest after the Kth occurrence.
Using a Loop
Using a loop with string manipulation allows us to iterate over each character or a substring enabling us to perform operations such as transforming, filtering, or counting elements.
Python
s = "hello,world,how,are,you"
k = 2
char = ","
count = 0 #
# Creating an empty list to store characters up to the k-th occurrence of the delimiter
result = []
for i in range(len(s)):
result.append(s[i]) # Appending each character to the result list
if s[i] == char: # If the character is a comma, increment the count
count += 1
if count == k: # If the k-th comma is found, stop further iterations
break
# Joining the result list and adding the remaining part of the string after the k-th comma
res = ''.join(result) + s[i + 1:]
print(res)
Outputhello,world,how,are,you
Explanation:
- Iterate over the string and append characters to the result list until the Kth occurrence of the character is found.
- After the Kth occurrence, append the rest of the string starting from the next character
Using re.split
with a Pattern
re.split()
method in Python allows splitting a string based on a regular expression pattern. This method provides more flexibility than the standard split()
by enabling complex delimiter patterns.
Python
import re
s = "hello,world,how,are,you"
k = 2
char = ","
pattern = f"({re.escape(char)})"
parts = re.split(pattern, s, maxsplit=k)
res = ''.join(parts[:k+1])
print(res)
Explanation:
re.split
splits the string up to the Kth occurrence of the character.- Regular expression captures the character itself, and the result is joined back to preserve the separator.
Similar Reads
Split String of list on K character in Python In this article, we will explore various methods to split string of list on K character in Python. The simplest way to do is by using a loop and split().Using Loop and split()In this method, we'll iterate through each word in the list using for loop and split it based on given K character using spli
2 min read
Python - Extract String after Nth occurrence of K character Given a String, extract the string after Nth occurrence of a character. Input : test_str = 'geekforgeeks', K = "e", N = 2 Output : kforgeeks Explanation : After 2nd occur. of "e" string is extracted. Input : test_str = 'geekforgeeks', K = "e", N = 4 Output : ks Explanation : After 4th occur. of "e"
7 min read
Python | K Character Split String The problems and at the same time applications of list splitting is quite common while working with python strings. Some characters are usually tend to ignore in the use cases. But sometimes, we might not need to omit those characters but include them in our programming output. Letâs discuss certain
4 min read
Split on last occurrence of delimiter-Python The goal here is to split a string into two parts based on the last occurrence of a specific delimiter, such as a comma or space. For example, given the string "gfg, is, good, better, and best", we want to split it into two parts, everything before the last comma-space and everything after it. The r
3 min read
Split String into List of characters in Python We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately. For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g'].Using ListThe simplest way t
2 min read