python - 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 /?
解决方案
您可以使用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
推荐阅读
- flask - addtionalProperties 未得到验证 (flasgger==0.9.2)
- r - R中的For循环(如果不是NA则打印)
- javascript - 使用 appendChild(iDiv) 向 div 元素添加点击事件时获取错误参数
- amazon-web-services - S3Exception with AWS SDK for Java version 2 - 我们计算的请求签名与您提供的签名不匹配
- python-3.x - Keras 形状:TypeError:“元组”对象不可调用
- api - paypal 授权 unsupported_grant_type 授予类型在 axios 发布请求中为 NULL
- c++ - 将 std::string 上的 std::replace 无效操作数替换为二进制表达式
- python - 创建具有默认值的多维数组的紧凑方法是什么?
- javascript - Angular HTTP 请求延迟拦截器未按预期工作
- python - 如何在 VGG16-CNN 中一次输入多张图像?