在第二次出现字符后拆分文本 [英] Split text after the second occurrence of character
问题描述
我需要在第二次出现-"字符之前拆分文本.我现在所拥有的是产生不一致的结果.我尝试了 rsplit
的各种组合,并通读并尝试了其他解决方案,但没有结果.
要拆分的示例文件名:'some-sample-filename-to-split'
在 data.filename
中返回.在这种情况下,我只想返回 'some-sample'
.
fname, extname = os.path.splitext(data.filename)file_label = fname.rsplit('/',1)[-1]file_label2 = file_label.rsplit('-',maxsplit=3)打印(file_label2,'\n','--------------','\n')
你可以这样做:
<预><代码>>>>a =一些样本文件名到拆分";>>>"-".join(a.split("-", 2)[:2])'一些样本'a.split("-", 2)
会将字符串拆分到第二次出现 -
为止.
a.split("-", 2)[:2]
将给出列表中的前 2 个元素.然后简单地加入前 2 个元素.
或
你可以使用正则表达式:^([\w]+-[\w]+)
正如评论中所讨论的,这是您需要的:
def hyphen_split(a):如果 a.count("-") == 1:return a.split("-")[0]返回-".join(a.split(-", 2)[:2])>>>连字符_拆分(一些样本文件名到拆分")'一些样本'>>>连字符_分裂(一些样本")'一些'
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')
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'
这篇关于在第二次出现字符后拆分文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!