开发者社区 问答 正文

如何从字符串中删除括号和字符串

从字面上看,我一直在尝试解决此问题的方法,但似乎我对正则表达式并不满意;)

我需要从列表中的字符串中删除(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')]

基本上是列表中的元组。

展开
收起
祖安文状元 2020-02-21 14:00:09 872 分享
分享
版权
举报
1 条回答
写回答
取消 提交回答
  • 您可以使用以下方式完成此操作re.findall:

    >>> cleaned_x = [tuple(re.findall(r"[A-Z]:/[^']+", a)) for a in x]
    >>> 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')]
    >>>
    
    2020-02-21 14:01:00 举报
    赞同 评论

    评论

    全部评论 (0)

    登录后可评论
问答分类:
问答地址: