简体   繁体   English

Python:读取txt文件后为string.replace(“ \\'”,“'”)

[英]Python: string.replace(“\'”,“'”) after reading txt file

When opening and reading a file containing the mark ' (like in the word shouldn't), python replaces it with \\' (which ends up being shouldn\\'t). 当打开并读取包含标记'的文件时(就像在单词中不应该这样),python将其替换为''(最终不应该)。 I tried running the following code: 我尝试运行以下代码:

a=open("file.txt")
b=a.read()
b=b.replace("\'", "'")

But b remains the same after running the third line, maybe because it reads "\\'" as if it were "'". 但是在运行第三行之后b仍然是相同的,可能是因为它读起来像“'”,好像它是“'”。 Please help. 请帮忙。

You need to double the slash: 你需要加倍斜杠:

b=b.replace("\\'", "'")

or use a r"" raw string literal: 或使用r""原始字符串文字:

b=b.replace(r"\'", "'")

Without the doubled slash or raw string literal, the \\' is interpreted as an espace code meaning ' . 如果没有doubled斜杠或原始字符串文字, \\'被解释为espace代码,意思是'

Do doublecheck that you are not looking at a string representation where python represents ' characters using the escape code: 双重检查您没有查看字符串表示,其中python 表示使用转义码'字符:

>>> '"' + "'"
'"\''
>>> print '"' + "'"
"'

In the above example I create a string with both a double and a single quote character ( "' ) and Python echoes that back to me as a string representation. Using print prints the actual string contents and not a representation. Note how Python has escaped the ' quote for me there. 在上面的例子中,我创建了一个包含双引号和单引号字符( "' )的字符串,Python回显给我作为字符串表示。使用print打印实际的字符串内容而不是表示。请注意Python是如何转义的在'报价为我那里。

"\\'" is the same as "'". “\\'“ 是相同的 ”'”。 The backslash escapes the ' so it doesn't do its special function. 反斜杠转义了',所以它没有执行其特殊功能。 That feature is useful if you have a single quoted string. 如果您有一个带引号的字符串,那么该功能非常有用。 For example the string '"shouldn\\'t"' is printed as "shouldn't". 例如,字符串“” shouldn \\'t“”被打印为“ should n't”。

Python 3.3.0 (default, Dec 22 2012, 21:02:07) 
[GCC 4.7.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'shouldn't'
  File "<stdin>", line 1
    a = 'shouldn't'
                 ^
SyntaxError: invalid syntax
>>> a = 'shouldn\'t'
>>> a
"shouldn't"
>>> a = '"shouldn\'t'
>>> a
'"shouldn\'t'
>>> print(a)
"shouldn't

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM