![](/img/trans.png)
[英]re.sub() - Regex for replacing last occurance of a substring in a string
[英]Get a substring after the last occurance of a string in Python
我有一个像这样的字符串:
test = "/home/myself/Downloads/example.py"
我想获得最后一次出现的/
之后的文本,即example.py
。 我尝试使用split:
test.split("/")[0]
但是问题是它会返回一个带有固定索引的字符串,这是我通常没有的。
上次出现/后如何获取字符串?
您可以让os
为您做:
import os
test = "/home/myself/Downloads/example.py"
os.path.basename(test) # -> example.py
尝试使用
test.split("/")[-1]
负索引在python的列表中向后移动,因此可以访问最后一个元素
您可以使用pop
方法。
print(test.split("/").pop())
pop
方法比slicing
更快。
import timeit
t1 = timeit.Timer('test = "/home/myself/Downloads/example.py";test.split("/").pop()')
t2 = timeit.Timer('test = "/home/myself/Downloads/example.py";test.split("/")[-1]')
输出量
t1 = 9.307525000622263e-07
t2 = 8.126347900179098e-06
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.