从多个字符串中删除引号

时间:2017-10-19 09:16:51

标签: python

我尝试重命名替换' VV'与VV

alist = ["py'VV'1.File.md",
 "py'VV'3.Database.md",
 "py'VV'Projects.md",
 "py'VV'2.Input.md"]

我想要的输出:

newlist = ["pyVV1.File.md",
 "pyVV3.Database.md",
 "pyVVProjects.md",
 "pyVV2.Input.md"]

我的解决方案

[i.replace("'VV'",'VV') for i in alist]
Out[158]: ['pyVV1.File.md', 'pyVV3.Database.md', 'pyVVProjects.md', 'pyVV2.Input.md']

如何通过魔法访问处理它以自动消除引用' '

例如:

In [163]: eval('str')
Out[163]: str

2 个答案:

答案 0 :(得分:2)

尝试以下代码

[x.replace("'", "") for x in alist]
#O/p: ['pyVV1.File.md', 'pyVV3.Database.md', 'pyVVProjects.md', 'pyVV2.Input.md']

你的也是正确的,但是如果你想要替换列表中每个字符串的任何单引号,那么上面应该可行。 (它将取代"' VV'"" VV"以及"' anychar'"到&# 34; anychar")。希望它有所帮助。

答案 1 :(得分:-1)

您可以使用正则表达式删除引号:

import  re

alist = ["py'VV'1.File.md",
 "py'VV'3.Database.md",
 "py'Pass'Projects.md",
 "py'VX'2.Input.md"]

pattern = r'\'(.*?)\''
blist = [re.sub(pattern, lambda x : x.group(1), s) for s in alist]

print(blist)