Python 删除带有条件的报价
如果我想从以下词语中删除引号:Python 删除带有条件的报价,python,Python,如果我想从以下词语中删除引号: don't hello' world' 我该如何做才能只删除第二个和第三个的引用。i、 e.我想做的是,如果没有两个字母包围,我只删除引用,并且最终结果如下: don't hello world import re re.sub('(?:(?<=\w)[\'\"](?:\W))|(?:(?<=\W)[\'\"](?:\w))', '', test_string) 希望这是有意义的。您可以使用regex实现这一点,但它确实不需要它。让我知道这是否是
don't
hello'
world'
我该如何做才能只删除第二个和第三个的引用。i、 e.我想做的是,如果没有两个字母包围,我只删除引用,并且最终结果如下:
don't
hello
world
import re
re.sub('(?:(?<=\w)[\'\"](?:\W))|(?:(?<=\W)[\'\"](?:\w))', '', test_string)
希望这是有意义的。您可以使用
regex
实现这一点,但它确实不需要它。让我知道这是否是对你问题的一种不准确的治疗,但你似乎可以按照以下思路做一些事情:
if not test_string.endswith("'"):
test_string.replace("'", "")
如果您确实想使用regex
(这可能是一个很好的选择,具体取决于您的应用程序),您可以执行以下操作:
don't
hello
world
import re
re.sub('(?:(?<=\w)[\'\"](?:\W))|(?:(?<=\W)[\'\"](?:\w))', '', test_string)
重新导入
re.sub('(?:(?试试这个:
words = ["don't", "hello'", "world'"]
quotes = ["'", '"']
output = list()
for word in words:
if word[-1] in quotes:
word = word[: (len(word) - 1)]
output.append(word)
print output
#=> ["don't", "hello", "world"]
我假设您还希望处理这样的情况,即除了单个报价之外,不需要的报价可能是双报价,“
。如果不是,您可以使用:
if word[-1] === "'":
你可以试试这个:
string = "hello'"
if string[-1] == "'":
string = string[:len(string) - 2]