Python: split text after second occurrence of character

I need to split the text before the second input of the '-' character. Now I have inconsistent results. I tried various combinations of rsplit and read and tried other solutions on SO, with no results.

Sample file name to split: some-sample-filename-to-splitreturns to data.filename. In this case, I would like to return 'some-sample'.

fname, extname = os.path.splitext(data.filename)
file_label = fname.rsplit('/',1)[-1]
file_label2 = file_label.rsplit('-',maxsplit=3)
print(file_label2,'\n','---------------','\n')
+4
source share
3 answers

You can do something like this:

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

a.split("-", 2)will split the line before the second occurrence -.

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

OR

You can use regex: ^([\w]+-[\w]+)

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

EDIT: , :

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

>>> hyphen_split("some-sample-filename-to-split")
'some-sample'
>>> hyphen_split("some-sample")
'some'
+8

:

import re

file_label = re.search('(.*?-.*?)-', fname).group(1)
+1

You can use str.index():

def hyphen_split(s):
    pos = s.index('-')
    try:
        return s[:s.index('-', pos + 1)]
    except ValueError:
        return s[:pos]

Test:

>>> hyphen_split("some-sample-filename-to-split")
'some-sample'
>>> hyphen_split("some-sample")
'some'
0
source

All Articles