Reputation: 21
I'm new to Python and recently in a class I am taking we started the dragon realm tutorial. http://inventwithpython.com/chapter6.html I decided to go way off on my own with this little project and make a semi-long adventure story. About half way through I started pasting my text into Word. (I was using a previous adventure story I had made in flash so all the test had already been written up). I started pasting into word so I could replace ' with ' and " with \" faster, since there were a lot of them and it took up a lot of time. When I ran it I noticed something odd. The text I had copied directly from Flash had needed the backslash to show ' or " properly, but the text I had copied from Word didn't. When I ran it, the text I had copied from word would show the backslashes.
for example:
\”This the newbie?\” The blond asked. \”Yep Lily,\” Rachel answered cheerfully.
This is what will show when I'm running it. If I take out the backslashes and run it it will print:
”This the newbie?” The blond asked. ”Yep Lily,” Rachel answered cheerfully.
But the text I copied from Flash works as it should with the backslashes, and if I were to take them out it would cause an error of some sort.
Can someone please explain to me why if I copy text from Word it makes the need for the backslash unnecessary? In case anyone was wondering I was working in Python 3.2.2 I haven't tested it in 2.7.
Upvotes: 2
Views: 1088
Reputation: 1122242
Word is a terrible code editor.
The quotes were replaced by a 'fancy' quote, not the normal double-quote from the ASCII alphabet, but one from elsewhere in the Unicode standard:
>>> u'”'
u'\u201d'
My Unicode application tells me that's the RIGHT DOUBLE QUOTATION MARK symbol; Word normally uses matching LEFT DOUBLE QUOTATION MARK symbols as well.
If you want to use double qoutes in your python string, simply enclose the whole string in single quote marks:
'I am a string with a double (") quote'
Or you can use tripple-quoting:
"""I am a string with both singe (') *and* double (") quotes"""
That way you don't have to bother with all those escapes.
Upvotes: 7
Reputation: 250971
It's because \
ecapes the "
, and python didn't finds any closing quotes in string, so it raises EOL
error:
In [19]: "This the newbie\ " #add a space after `\` and it works
Out[19]: 'This the newbie\\ '
In [20]: "This the newbie\"
------------------------------------------------------------
File "<ipython console>", line 1
"This the newbie\"
^
SyntaxError: EOL while scanning string literal
In [22]: "\"This the newbie\""
Out[22]: '"This the newbie"'
Upvotes: 0