I need to split text before the second occurrence of the '-' character. What I have now is producing inconsistent results. I've tried various combinations of rsplit
and read through and tried other solutions on SO, with no results.
Sample file name to split: 'some-sample-filename-to-split'
returned in data.filename
. In this case, I would only like to have 'some-sample'
returned.
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')
a. split("-", 2) will split the string upto the second occurrence of - . a.
You can find the nth occurrence of a substring in a string by splitting at the substring with max n+1 splits. If the resulting list has a size greater than n+1, it means that the substring occurs more than n times.
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 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.
OR
You could use regular expression : ^([\w]+-[\w]+)
>>> import re >>> reg = r'^([\w]+-[\w]+)' >>> re.match(reg, a).group() 'some-sample'
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") 'some-sample' >>> hyphen_split("some-sample") 'some'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With