python:提取某些弦的一部分

2024-03-28 10:37:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,我想从中提取某些部分。字符串看起来像:

 E:/test/my_code/content/dir/disp_temp_2.hgx

这是机器上扩展名为hgx的特定文件的路径

我很想拍下“disp_temp_2”。问题是我使用了strip函数,不适合我,因为有很多'/'。另一个问题是,上面的位置总是在计算机上改变。在

有没有什么方法可以让我捕获最后一个“/”和“.”之间的确切字符串

我的代码看起来像:

^{pr2}$

。。现在我不能根据最后一个“/”进行拆分。在

有什么办法吗?在

谢谢


Tags: 文件函数字符串test路径机器my计算机
3条回答

Python附带了^{}模块,它为您提供了更好的处理路径和文件名的工具:

>>> import os.path
>>> p = "E:/test/my_code/content/dir/disp_temp_2.hgx"
>>> head, tail = os.path.split(p)
>>> tail
'disp_temp_2.hgx'
>>> os.path.splitext(tail)
('disp_temp_2', '.hgx')

使用操作系统路径模块:

import os.path
filename = "E:/test/my_code/content/dir/disp_temp_2.hgx"
name = os.path.basename(filename).split('.')[0]

标准lib很酷:

>>> from os import path
>>> f = "E:/test/my_code/content/dir/disp_temp_2.hgx"
>>> path.split(f)[1].rsplit('.', 1)[0]
'disp_temp_2'

相关问题 更多 >