You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何按条件截取字符串尾部?附图片路径处理需求

嘿,针对你这个路径处理的需求,我给你两个靠谱的Python实现方案,都是用内置模块,比手动字符串操作更健壮,能避免不同系统路径分隔符的坑:

方案1:使用Python3.4+推荐的pathlib(面向对象路径处理)

这个模块是Python官方推荐的现代路径处理方式,代码更直观易读:

from pathlib import Path

myString = "D:/Train/16_partitions_annotated/partition1/images/AAAAA/073-1_00191.jpeg"
# 把字符串转为Path对象
img_path = Path(myString)

# 1. 提取文件名(就是你需要单独保存的部分)
filename = img_path.name

# 2. 处理父目录:替换"images"为"IMAGES"
parent_parts = list(img_path.parent.parts)  # 获取文件父目录的所有组成部分
for idx, part in enumerate(parent_parts):
    if part == "images":
        parent_parts[idx] = "IMAGES"
        break  # 找到第一个匹配项就停止,避免多替换

# 重新组合成路径,加空字符串确保结尾带斜杠
new_path = Path(*parent_parts) / ""
newString = str(new_path)

# 验证结果
print(newString)  # 输出: D:/Train/16_partitions_annotated/partition1/IMAGES/AAAAA/
print(filename)   # 输出: 073-1_00191.jpeg
方案2:使用传统的os.path模块(兼容所有Python版本)

如果你的项目还在使用Python3.4之前的版本,用这个方案更稳妥:

import os

myString = "D:/Train/16_partitions_annotated/partition1/images/AAAAA/073-1_00191.jpeg"
# 分离目录路径和文件名
dir_path, filename = os.path.split(myString)

# 替换目录中的"images"为"IMAGES"
new_dir_path = dir_path.replace("images", "IMAGES")

# 确保路径结尾带斜杠(如果不需要可以去掉这一步)
newString = os.path.join(new_dir_path, "")

# 验证结果
print(newString)  # 输出: D:/Train/16_partitions_annotated/partition1/IMAGES/AAAAA/
print(filename)   # 输出: 073-1_00191.jpeg

为什么推荐用内置模块而不是手动字符串操作?

因为不同操作系统的路径分隔符不一样(Windows是\,Linux/macOS是/),pathlib和os.path会自动适配这些差异,而且能避免手动拆分字符串时可能出现的边界错误(比如路径中多次出现"images"的情况,你可以根据需求调整是否替换所有匹配项)。

内容的提问来源于stack exchange,提问作者bit_scientist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:55:10