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

时间:2020-02-21 05:21:26

标签: python regex python-3.x string split

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

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

基本上是列表中的元组。

3 个答案:

答案 0 :(得分:2)

您可以这样使用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')]
>>> 

希望有帮助。

答案 1 :(得分:2)

也许您可以使用捕获组?例如:

import re

re_winpath = re.compile(r'^\(WindowsPath\(\'(.*)\'\)\,WindowsPath\(\'(.*)\'\)\)$')

def extract_pair(s):
    m = re_winpath.match(s)
    if m is None:
        raise ValueError(f"cannot extract pair from string: {s}")
    return m.groups()

pairs = list(map(extract_pair, x))

答案 2 :(得分:1)

这是我的主意,

不是很漂亮,我分两步进行操作,以免制作正则表达式意大利细面条,并且您可以根据需要将其转换为列表理解功能,但是应该可以使用

for a in x:
    a = re.sub('(\()?WindowsPath', '', a)
    a = re.sub('\)$','', a)
    print(a)
相关问题