无法用多个转义字符替换字符串

2024-09-27 17:56:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用replace()方法时遇到了问题。我想替换字符串的某些部分,而我想替换的部分由多个转义字符组成。它看起来像这样的东西

['<div class=\"content\">rn

要删除它,我有一个代码块

garbage_text = "[\'<div class=\\\"content\\\">rn    "
entry = entry.replace(garbage_text,"")

但是,它不起作用。从我的整个字符串中删除任何内容。有人能指出我到底哪里想错了吗?提前谢谢。你知道吗

添加:

完整的字符串如下所示

"['<div class=\"content\">rn    gitar calmak icin kullanilan minik plastik garip nesne.rn  </div>']"

Tags: 方法字符串代码textdiv内容rncontent
2条回答

也许您的“条目”格式不正确?你知道吗

在Python 3.6.7中,通过一个额外的变量“text”,可以实现以下功能:

>>> garbage_text
'[\'<div class=\\\'content\'\\">rn     '
>>> text
'[\'<div class=\\\'content\'\\">rn     And then there were none'
>>> entry = text.replace(garbage_text, "")
>>> entry
'And then there were none'

您可以对替换字符串使用三重引号格式,这样就不必费心转义了:

garbage_text = """['<div class="content">rn    """

相关问题 更多 >

    热门问题