【问题标题】:How to remove WindowsPath and parantheses from a string [duplicate]如何从字符串中删除 Windows 路径和括号 [重复]
【发布时间】:2020-06-05 06:17:25
【问题描述】:

我需要从目录字符串中删除WindowsPath( 和一些右括号)

x= (WindowsPath('D:/test/1_birds_bp.png'),WindowsPath('D:/test/1_eagle_mp.png'))

我需要的是

x= ('D:/test/1_birds_bp.png', 'D:/test/1_eagle_mp.png')

我不知道如何同时处理多个字符串。

通过关注@MonkeyZeus 我试过了;

y = [re.sub("(?<=WindowsPath\(').*?(?='\))",'',a) for  a in x]

TypeError:预期的字符串或类似字节的对象

【问题讨论】:

  • 这里显示的不是字符串,而是两个WindowsPath 对象的元组。如果您的问题是“如何将这些对象转换为字符串”,那么答案是:x = [ str(e) for e in x]
  • @Błotosmętek 不,我的问题是如何删除它们。
  • @anubhava 好的,请看 OP!

标签: python regex string split strip


【解决方案1】:

您可以通过以下方式轻松定位路径:

(?<=WindowsPath\(').*?(?='\))
  • (?&lt;=WindowsPath\(') - 左侧必须是 WindowsPath('
  • .*? - 懒惰地捕捉一切,直到我们达到积极的前瞻性
  • (?='\)) - 从字面上看') 的积极前瞻

https://regex101.com/r/GrIY4I/1/

【讨论】:

  • 您能补充一下如何将 apply 应用于 x 吗?
【解决方案2】:
x= "(WindowsPath('D:/test/1_birds_bp.png'),WindowsPath('D:/test/1_eagle_mp.png'))"

x.replace('WindowsPath(','').replace('(','').replace(')','')

输出:

'D:/test/1_birds_bp.png','D:/test/1_eagle_mp.png'

【讨论】:

  • 你能匹配预期的输出吗?
猜你喜欢
  • 1970-01-01
  • 2019-10-12
  • 1970-01-01
  • 1970-01-01
  • 2021-01-29
  • 2018-08-16
  • 1970-01-01
  • 2013-08-12
  • 1970-01-01
相关资源
最近更新 更多