我喜欢简化我的代码,以便在 / 之后获得最后一个字
有什么建议吗?
def downloadRepo(repo):
pos1=repo[::-1].index("/")
salida=repo[::-1][:pos1]
print(salida[::-1])
downloadRepo("https://github.com/byt3bl33d3r/arpspoof")
提前致谢!
您可以使用str.rsplit
负索引:
"https://github.com/byt3bl33d3r/arpspoof".rsplit('/', 1)[-1]
# 'arpspoof'
您也可以坚持使用索引并使用str.rfind
:
s = "https://github.com/byt3bl33d3r/arpspoof"
index = s.rfind('/')
s[index+1:]
# 'arpspoof'
后者的内存效率更高,因为这些split
方法构建了包含所有拆分标记的内存列表,包括我们不使用的来自前面的虚假标记。
您可以使用
string = "https://github.com/byt3bl33d3r/arpspoof"
last_part = string.split("/")[-1]
print(last_part)
哪个产量
arpspoof
rsplit()
与split()
产量(在我的 Macbook Air 上)以下结果:
import timeit
def schwobaseggl():
return "https://github.com/byt3bl33d3r/arpspoof".rsplit('/', 1)[-1]
def jan():
return "https://github.com/byt3bl33d3r/arpspoof".split("/")[-1]
print(timeit.timeit(schwobaseggl, number=10**6))
print(timeit.timeit(jan, number=10**6))
# 0.347005844116
# 0.379151821136
因此,rsplit
替代方案确实稍微快一些(即运行 1.000.000 次)。