Removing backslashes from string
我早些时候回答了一个问题,在那里,操作人员问他如何从一根绳子上去掉反斜杠。这就是反斜杠在op字符串中的样子:
1 | "I don\'t know why I don\'t have the right answer" |
这是我的答案:
1 2 3 | a ="I don\'t know why I don\'t have the right answer" b = a.strip("/") print b |
这消除了对字符串的反斜杠,但我的答案被否决了,我收到一条评论说"我的答案有很多问题,很难计算",我完全相信我的答案可能是错误的,但我想知道为什么这样我才能从中学习。但是,作者删除了那个问题,所以我无法回复那里的评论来问这个问题。
1 2 3 | a ="I don\'t know why I don\'t have the right answer" b = a.strip("/") print b |
也许还有一些元问题:
无论如何,这不算太多。
然而,评论并没有说这是太多了计数,只是很难计数。有些人很难数到fourthree。即使是英国的国王也必须由他们的神职人员提醒如何去做。
嗯,绳子里没有斜杠,也没有反斜杠。反斜杠退出了
1 2 | print("I don\'t know why I don\'t have the right answer") print("I don't know why I don't have the right answer") |
生产:
1 2 | I don't know why I don't have the right answer I don't know why I don't have the right answer |
此外,您使用了错误的字符,并且
1 2 3 | Python 2.7.9 (default, Mar 1 2015, 12:57:24) >>> print("///I don't know why ///I don't have the right answer///".strip("/")) I don't know why ///I don't have the right answer |
要将反斜杠放到字符串中,还需要对其进行转义(或使用原始字符串文本)。
1 2 | >>> print("\\I don't know why ///I don't have the right answer\".strip("/")) \I don't know why ///I don't have the right answer\ |
正如你所看到的,即使反斜杠在字符串的开始和结束处,它们也没有被删除。
最后,回答最初的问题。一种方法是对字符串使用
1 2 | >>> print("\\I don't know why \\\I don't have the right answer\".replace("\","")) I don't know why I don't have the right answer |
还有,在你弄错自己的答案之后,寻求一个好答案的道具。
我来描述一下整件事
1 2 | a ="I don\'t know why I don\'t have the right answer" ^ ^ |
在这里,您可以看到两个斜杠实际上都在转义字符
现在来看看你的代码,
Return a copy of the string with the leading and trailing characters removed
因此,在编写代码时,您不是删除反斜杠,而是删除字符串末尾的正斜杠(如果有的话)!
1 | b = a.strip("/") |
但是,在显示时不会出现反斜杠。这是因为反斜杠只用于内部的Python表示,当您打印它们时,它们将被解释为它们的转义字符,因此您将看不到反斜杠。您可以看到
但需要注意的是,在使用
1 | a ="I don't know why I don't have the right answer" |
足够了!
在官方的python文档中,这个主题被广泛地介绍了
1
2
3
4
5
6 >>> 'spam eggs' # single quotes
'spam eggs'
>>> 'doesn\'t' # use \' to escape the single quote...
"doesn't"
>>>"doesn't" # ...or use double quotes instead
"doesn't"
以上代码段直接取自文档。
1 2 3 4 | In [7]: a ="I don\'t know why I don\'t have the right answer" In [8]: a Out[8]:"I don't know why I don't have the right answer" |
单引号:
1 2 3 4 | In [19]: a = 'I don\'t know why I don\'t have the right answer' In [20]: a Out[20]:"I don't know why I don't have the right answer" |
如果您试图从字符串中删除实际的
The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.