[cdalten@localhost ~]$ python
Python 2.6.2 (r262:71600, May 3 2009, 17:04:44)
[GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "test \"
File "<stdin>", line 1
print "test \"
^
SyntaxError: EOL while scanning string literal
>>>
I mean, isn't the '\' a character just like the letter 't'?
print "\\"
\ is the escape character, it masks the meaning of the next chararcter.
If you write print "\" python tries to print " (the meaning of " as
the string delimiter is beeing masked) and finds no closing "
This is why you got the error.
hth.
Greetings
Hans
So something like
"\"
changes the meaning of " ? How? Does it just shift the ASCII bit(s)?
No. There is a fixed set of "escape sequences" as they're called.
The Fine Manual lists them here:
http://docs.python.org/reference/lexical_analysis.html#literals
--
Rhodri James *-* Wildebeeste Herder to the Masses
print r'test \'
print r'test \\'
Because of the way raw string parsing is defined, neither of these will
pass the parser. In fact, a raw string cannot have a backslash as
its last character.
No, the Python parser handles it when it parses string literals.
Cheers,
Chris
--
http://blog.rebertia.com
Tried it:
>>> r'test \'
SyntaxError: EOL while scanning string literal
>>> r'test \\'
'test \\\\'
Second one is accepted. See the language reference section 2.4.1 as of
why; http://www.python.org/doc/current/reference/lexical_analysis.html?highlight=raw%20strings#string-literals
/Niklas Norrthon
Ask yourself: 'How would I tell Python to print the " character when
it's used as the string delimitation character?'. Unlike us (you
probably didn't even blink at the usage of ' in "it's" versus its
usage as quote delimiters in that sentence), computers can't quite
tell usage from context. So you have to come up with a way to express
ourselves. Many languages use the \ character as an escape character,
which modifies the meaning of the next character in a string. \n, \t,
\" are all common. Other languages use other conventions -- I program
ABAP professionally, and it uses ' as the string delimiter, and '' as
a literal -- so a string with one single ' is expressed as ''''.
The python interpreter isn't doing any bit magic here, it's just
reading a \ character followed by a " character and changing its
interpretation of " appropriately.
>JG> And as an interesting exercise, try
>JG> print r'test \'
>JG> print r'test \\'
>JG> Because of the way raw string parsing is defined, neither of these will
>JG> pass the parser. In fact, a raw string cannot have a backslash as
>JG> its last character.
Cannot have an odd number of backslashes as its last characters.
>>> print r'test \\'
test \\
--
Piet van Oostrum <pi...@cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: pi...@vanoostrum.org