替换字符串中的通配符

2024-09-29 21:31:04 发布

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

我有一个脚本正在创建一个变量,如下所示:

ex = "/Volumes/Obelix/5215.tif, /Volumes/Gemeinsam/25.tif, /Volumes/Obelix/5100.tif"

是否可以使用/Volumes/Gemeinsam/*删除所有内容,因此我最终得到:

^{pr2}$

我不习惯Python中的通配符,所以我有一些问题。我读了很多关于re.sub()的文章,但在这里却没法用。在


Tags: re脚本内容文章ex习惯tifvolumes
2条回答

Python并不真正处理通配符。Python中的Regex不应该更具体。在

在任何情况下,都应注意:

ex = "/Volumes/Obelix/5215.tif, /Volumes/Gemeinsam/25.tif, /Volumes/Obelix/5100.tif"
newex = re.sub(r'/Volumes/Gemeinsam/.+?,?(\s|$)', '', ex)

根据您对数据的确定程度,您将不得不做一些预解析,但是您可以使用inin运算符来检查一个字符串是否包含另一个字符串。然后,您可以根据最可读的内容使用循环或列表理解。在

ex = [x.strip() for x in "/Volumes/Obelix/5215.tif, /Volumes/Gemeinsam/25.tif, /Volumes/Obelix/5100.tif".split(',')]
check = "/Volumes/Gemeinsam"
new_ex = [x for x in ex if check not in x]

相关问题 更多 >

    热门问题