我有从API请求中获取的字符串...
It was quick and great ! And it\\\\'s customized
我想删除所有四个反斜杠(在撇号之前)。
这是代码所在的地方...
reviews = reviews_response.json()
filtered_reviews = []
for key, review in reviews.items():
comment = review.get('textcomments')
comment = comment.replace(r"\\'", "'")
if len(comment) > 30:
filtered_reviews.append(review)
在这个特定的示例中,当我在PyCharm中逐步进行操作时,该变量comment
在replace()
执行后永不更改。我已经尝试过这些事情,但都没有成功...
regex = re.compile(r"\\\\")
comment = "It was quick and great ! And it\\\\'s customized"
comment = regex.sub('', comment)
comment = re.sub(r"(\\){4}", '', comment)
comment = re.sub(r"\\\\\\\\'", '', comment)
comment = comment.replace('\\\\\\\\', "")
comment = comment.replace('\\\\\\\\\'', "")
comment = comment.replace('\\\\\'', "")
comment = comment.replace("\\\\", "")
我希望它看起来像这样...
It was quick and great ! And it's customized
在弄清楚这一点之后,我遇到了两个主要问题。
我遇到的主要问题是PyCharm给了我错误的价值。实际值为It was quick and great ! And it\\'s customized
在附加comment
到review
之前,我没有保存返回的结果filtered_reviews
谢谢大家的评论和帮助。
您不需要正则表达式,在反斜杠后查找撇号,然后仅用撇号替换整个模式:
In [1]: s = "It was quick and great ! And it\\\\'s customized"
In [2]: s.replace(r"\\'", "'")
Out[2]: "It was quick and great ! And it's customized"
根据您的repr输出,您不会有多个反斜线:
Out[4]: u"It was quick and great ! And it\\'s customized"
In [5]: s.replace(r"\'","'")
Out[5]: u"It was quick and great ! And it's customized"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句