Split string on the Nth occurrence of a character in Python

avatar

Borislav Hadzhiev

Last updated: Jun 24, 2022

banner

Photo from Unsplash

Split string on the Nth occurrence of a character in Python #

To split a string on the Nth occurrence of a character:

  1. Use the split() method to split the string into a list.
  2. Use the join() function to join a subset of the list (0 to N).
  3. Use the join() function to join a subset of the list (N until the end).
main.py
my_str = 'one-two-three-four' my_list = my_str.split('-') print(my_list) # 👉️ ['one', 'two', 'three', 'four'] n = 2 first = '-'.join(my_list[:n]) second = '-'.join(my_list[n:]) print(first) # 👉️ 'one-two' print(second) # 👉️ 'three-four'

The first step is to use the str.split() method to split the string into a list.

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)

Once we have a list of strings, we can use the str.join() method to join slices of the list with the same delimiter.

main.py
my_str = 'one-two-three-four' my_list = my_str.split('-') print(my_list) # 👉️ ['one', 'two', 'three', 'four'] n = 2 print(my_list[:n]) # ['one', 'two'] print(my_list[n:]) # ['three', 'four'] first = '-'.join(my_list[:n]) second = '-'.join(my_list[n:]) print(first) # 👉️ 'one-two' print(second) # 👉️ 'three-four'

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The syntax for list slicing is my_list[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive.

The my_list[:n] slice selects the first N items in the list, whereas the my_list[n:] slice selects the elements from index N to the end.

You can also perform the operation on a single line.

main.py
my_str = 'one-two-three-four' n = 2 first = '-'.join(my_str.split('-', n)[:n]) second = '-'.join(my_str.split('-', n)[n:]) print(first) # 👉️ 'one-two' print(second) # 👉️ 'three-four'

However, this is a bit harder to read than splitting the string into a list first.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.