Python – Split String After Second Occurrence of Separator

5/5 - (3 votes)

Coding Challenge

πŸ’¬ Question: Given a Python string. How to split the string after the second occurrence of the separator (string or character)? In other words: how to ignore the first separator occurrence when splitting a string?

Here are three examples:

  1. 'a-b-c-d-e-f-g-h' and sep='-' should be split to ['a-b', 'c', 'd', 'e', 'f', 'g', 'h']
  2. 'a-b' and sep='-' should be split to ['a-b']
  3. 'helloxxxworldxxxpythonxxxisxxxgreat' and sep='xxx' should be split to ['helloxxxworld', 'python', 'is', 'great']

Solution

You can split a string after the second occurrence of a given character in three steps:

  1. First, split the whole string using the separator sep in s.split(sep).
  2. Second, combine the first two elements of the resulting split list using the sep.join() method call.
  3. Third, use slicing and list concatenation to create a new result list.

The following code creates a function that takes as input a string s and a separator string sep and splits the string at the second occurrence:

def my_split(s, sep):
    all_split = s.split(sep)
    return [sep.join(all_split[0:2])] + all_split[2:]


print(my_split('a-b-c-d-e-f-g-h', '-'))
# ['a-b', 'c', 'd', 'e', 'f', 'g', 'h']


print(my_split('a-b', '-'))
# ['a-b']


print(my_split('helloxxxworldxxxpythonxxxisxxxgreat', 'xxx'))
# ['helloxxxworld', 'python', 'is', 'great']

The code does multiple things.

First, it creates a list all_split by splitting the string s using separator sep. For example, when using it on string 'a-b-c-d-e-f-g-h' and sep='-', it would return ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].

πŸ‘‰ Recommended Tutorial: Python String Split

Second, it combines the first two elements using the separator string sep between them by running sep.join(all_split[0:2]).

Recommended Tutorials: πŸ‘‡

Third, it puts the result into a list using the square bracket notation, i.e., we get a list with one string element ['a-b'] for our example.

πŸ‘‰ Recommended Tutorial: How to Create a Python List?

Fourth, you concatenate this list with the remaining all_split list, ignoring the first two split results, that are already merged to ignore the first split, by using the slicing expression all_split[2:].

In our example, we get ['a-b'] and ['c', 'd', 'e', 'f', 'g', 'h'] that concatenates to ['a-b', 'c', 'd', 'e', 'f', 'g', 'h'].

πŸ‘‰ Recommended Tutorials: List Concatenation in Python

Thanks for reading this short tutorial. To keep learning, feel free to join my 100% free email academy with cheat sheets and regular learning content!