我有以下代码删除“refs / changes / digit”但是没有得到预期的输出,我有如下所示的curent输出,任何人都可以提供输入 如何解决这个问题?
source="refs/changes/44/1025744/3 refs/changes/62/1025962/5 refs/changes/45/913745/2"
output = ' '.join(line.split('/', 3)[-1] for line in source.splitlines())
print output
CURRENT OUTPUT:-
1025744/3 refs/changes/62/1025962/5 refs/changes/45/913745/2
expected output
1025744/3 1025962/5 913745/2
答案 0 :(得分:2)
拆分空格然后拆分前三个"/"
并提取最后一个元素。
source="refs/changes/44/1025744/3 refs/changes/62/1025962/5 refs/changes/45/913745/2"
print(" ".join([ele.split("/",3)[-1] for ele in source.split()]))
1025744/3 1025962/5 913745/2
一些时间:
In [3]: import re
In [4]: timeit " ".join([ele.split("/",3)[-1] for ele in source.split()])
100000 loops, best of 3: 1.83 µs per loop
In [5]: timeit p.findall(source)
100000 loops, best of 3: 2.84 µs per loop
答案 1 :(得分:1)
另一种方法是使用正则表达式:
import re
p = re.compile(r'(\d{6,7}/\d{1})')
source="refs/changes/44/1025744/3 refs/changes/62/1025962/5 refs/changes/45/913745/2"
print p.findall(source)
请注意,我在斜杠前明确定义了6或7个字符的数字(您可以根据需要调整正则表达式)。