为什么此代码不会在Python中删除我的反斜杠?

时间:2019-07-05 18:45:11

标签: python string-formatting

我有一段代码是字符串格式的。它的变量名my_string如下所示:

'<div class="section page-centered"><div><b style="font-size: 24px">About 
Us</b></div><div>At <a href="https://close.com/" class="postings- 
link">Close</a>, we\'re building the sales
communication platform of the future. With our roots as the very first 
sales CRM to include built-in calling, we\'re leading the industry toward 
eliminating manual processes and helping compa
nies to close more deals (faster). Since our founding in 2013, we\'ve 
grown to become a profitable, 100% globally distributed team of ~33 high- 
performing, happy people that are dedicated to b
uilding a product our customers love. </div>'

除了反斜杠,我想将所有内容保留在该块中。我在这里看到了很多问题和解答,哪里可以找到解决方案

new_string = my_string.replace("\\", "")

但是我得到相同的输出。我在这里做什么错了?

2 个答案:

答案 0 :(得分:3)

反斜杠实际上是在转义单引号。如果我打印字符串,我将得到:

print('<div class ... </div>')

<div class="section page-centered"><div><b style="font-size: 24px">About Us</b></div><div>At <a href="https://close.com/" class="postings- link">Close</a>, we're building the salescommunication platform of the future. With our roots as the very first sales CRM to include built-in calling, we're leading the industry toward eliminating manual processes and helping companies to close more deals (faster). Since our founding in 2013, we've grown to become a profitable, 100% globally distributed team of ~33 high- performing, happy people that are dedicated to building a product our customers love. </div>

答案 1 :(得分:0)

我不确定为什么它可以在某些计算机上运行,​​但是至少在我的系统中存在此问题:

  • 后跟某事的强烈反对实际上不是双重反对,除非它是双重反对:

back_lash="hi\myname\is\backlash"
print(back_lash)

这将输出:

hi\myname\iacklash

在可以为其着色的IDE中更容易看到它。

Example

如您所见,它是一个非常特殊的字符。替换为双反冲

here中所述,它很难解决反弹问题。反斜杠(“ \”)字符用于转义具有特殊含义的字符,例如换行符,反斜杠本身或引号字符。 您可以使用前缀r或R:

字符串文字可以选择以字母'r'或'R'为前缀;这样的字符串称为原始字符串,并使用不同的规则来解释反斜杠转义序列。

r"Some string with \ backslash"

看看this,他们提到:

  

您需要在反斜杠前面加上另一个反斜杠   反斜杠\字符称为转义字符,它以不同的方式解释其后的字符。例如,n本身只是一个字母,但是当您在其前加反斜杠时,它变为\ n,这是换行符。

您可能会猜到,\也需要转义,因此它不像转义符那样起作用。本质上,您必须...逃脱。