简体   繁体   中英

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). 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 "'". Please help.

You need to double the slash:

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

or use a r"" raw string literal:

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

Without the doubled slash or raw string literal, the \\' is interpreted as an espace code meaning ' .

Do doublecheck that you are not looking at a string representation where python represents ' characters using the escape code:

>>> '"' + "'"
'"\''
>>> 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.

"\\'" 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".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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