Why is escaping single quotes incompatible with a file read in Python?

Given two almost identical text files (plain text created in MacVim), I get different results when reading them into a variable in Python. I want to know why this is so and how I can ensure consistent behavior.

For example, f1.txt looks like this:

This isn't a great example, but it works.

And f2.txt looks like this:

This isn't a great example, but it wasn't meant to be. 
"But doesn't it demonstrate the problem?," she said.

When I read these files, use something like the following:

f = open("f1.txt","r")
x = f.read()

I get the following when I look at variables in the console. f1.txt:

>>> x
"This isn't a great example, but it works.\n\n"

And f2.txt:

>>> y
'This isn\'t a great example, but it wasn\'t meant to be. \n"But doesn\'t it demonstrate the problem?," she said.\n\n'

In other words, f1 only comes in with escaped newlines, while f2 also has single quotes that have been escaped.

repr () shows what is happening. first for f1:

>>> repr(x)
'"This isn\'t a great example, but it works.\\n\\n"'

And f2:

>>> repr(y)
'\'This isn\\\'t a great example, but it wasn\\\'t meant to be. \\n"But doesn\\\'t it demonstrate the problem?," she said.\\n\\n\''

. ? , , , ( Javascript).

+4
2

Python , , Python, . repr() ( "" ) . , , , Python , .

, , . , . , ( , , ). .

, . repr() , Python. print , , .

JavaScript, - json:

import json
print json.dumps('I said, "Hello, world!"')
+15

f1 f2 .

, repr , .

. , :

"abc'def'ghi"
'abc\'def\'ghi'
'''abc'def'ghi'''
r"abc'def'ghi"

repr , , , . ( , , .)


, a repr, .

, , , . , . , CPython 3.3 unicode_repr ; , , , ' ".


"" , , . - , . , ; , - , . C, , JSON, , ASCII RFC822... ( Python), .

+7

All Articles