首页 > 解决方案 > Get a substring after the last occurance of a string in Python

问题描述

I have a string like:

test = "/home/myself/Downloads/example.py"

And I want to get the text after the last occurrence of /, which is example.py. I tried using split:

test.split("/")[0]

But the problem is that it would return the string with a fixed index, which I don't have usually.

How can I get the string after the last occurrence of /?

标签: python

解决方案


您可以使用str.split并获取索引-1,它是列表的最后一个元素。

test = "/home/myself/Downloads/example.py"
print(test.split("/")[-1]) # 'example.py'

虽然,在恢复文件名的特定情况下,来自Ev. Kounis展示了最好的方法。

你可以让它os为你做:

import os
test = "/home/myself/Downloads/example.py"
os.path.basename(test)  # -> example.py

推荐阅读