【发布时间】:2020-02-21 05:21:26
【问题描述】:
从字面上看,我一直在尝试解决这个问题的方法,但似乎我对正则表达式很差;)
我需要从列表中的字符串中删除 (WindowsPath 和 )"
x= ["(WindowsPath('D:/test/1_birds_bp.png'),WindowsPath('D:/test/1_eagle_mp.png'))", "(WindowsPath('D:/test/2_reptiles_bp.png'),WindowsPath('D:/test/2_crocodile_mp.png'))"]
所以我尝试了
import re
cleaned_x = [re.sub("(?<=WindowsPath\(').*?(?='\))",'',a) for a in x]
输出
["(WindowsPath(''),WindowsPath(''))", "(WindowsPath(''),WindowsPath(''))"]
我需要的是;
cleaned_x= [('D:/test/1_birds_bp.png','D:/test/1_eagle_mp.png'), ('D:/test/2_reptiles_bp.png','D:/test/2_crocodile_mp.png')]
基本上是列表中的元组。
【问题讨论】:
-
每个字符串都以
( WindowsPath (...))开头的时候为什么要使用re使用切片不是很容易吗? -
只是好奇-如果您只想删除它们(并且它们是您想要删除的固定子字符串),是否需要使用正则表达式?你不能使用标准的字符串替换()函数吗?
-
@Richard 任何能给出预期结果的东西都对我有用;)
-
...其实我又看了一遍,我认为你确实需要使用正则表达式。 ...稍等片刻:D
-
@Richard 你们是很好的帮助!感谢您的时间和努力!这是一个很棒的社区!
标签: python regex python-3.x string split