[Solved] Python split a string at an underscore


Assuming that you have a string with multiple instances of the same delimiter and you want to split at the nth delimiter, ignoring the others.

Here’s a solution using just split and join, without complicated regular expressions. This might be a bit easier to adapt to other delimiters and particularly other values of n.

def split_at(s, c, n):
    words = s.split(c)
    return c.join(words[:n]), c.join(words[n:])

Example:

>>> split_at('this_is_my_name_and_its_cool', '_', 2)
('this_is', 'my_name_and_its_cool')

1

solved Python split a string at an underscore