Split text after the second occurrence of character

You can do something like this:

>>> a = "some-sample-filename-to-split"
>>> "-".join(a.split("-", 2)[:2])

a.split("-", 2) will split the string upto the second occurrence of -.

a.split("-", 2)[:2] will give the first 2 elements in the list. Then simply join the first 2 elements.


You could use regular expression : ^([\w]+-[\w]+)

>>> import re
>>> reg = r'^([\w]+-[\w]+)'
>>> re.match(reg, a).group()

EDIT: As discussed in the comments, here is what you need:

def hyphen_split(a):
    if a.count("-") == 1:
        return a.split("-")[0]
    return "-".join(a.split("-", 2)[:2])

>>> hyphen_split("some-sample-filename-to-split")
>>> hyphen_split("some-sample")

Leave a Comment