[Tutor] How to replace the '\'s in a path with '/'s?
Steven D'Aprano
steve at pearwood.info
Sun Jul 31 10:03:09 CEST 2011
Richard D. Moores wrote:
> File "c:\P32Working\untitled-5.py", line 2
> return path.replace('\', '/')
> ^
> SyntaxError: EOL while scanning string literal
Others have already told you how to solve the immediate problem (namely,
escape the backslash), but I'd like to talk more about general
problem-solving techniques, in the principle that it is better to teach
someone how to catch their own fish rather than just to feed them fish
for a day.
As a programmer (amateur or profession), we *must* learn to read the
error messages and glean as much information as possible. In this case,
the error tells you that the line couldn't even be executed, because it
doesn't compile: you get a SyntaxError.
SyntaxErrors show you where the failure occurs: look at the ^ up-arrow
under the line of code. It points to the end of the line. Combine that
with the error message "EOL while scanning string literal" and the cause
of the error is solved: Python ran out of line before the string was closed.
(You may need to google on "EOL" to learn that it means "End Of Line".)
This of course opens more questions. Python, apparently, thinks that the
closing bracket ) is inside a string, instead of outside of it. Look at
the offending line and work backwards, and you should be able to see
that Python sees the line as:
return path.replace( AAA / BBB
where AAA is the string '\', ' and BBB is the broken string ')
This gives you a clue to try in the interactive interpreter. You should
*expect* this to raise an exception, but it does not:
>>> s = '\', '
>>> print s
',
>>> print repr(s)
"', "
which should lead you to googling on "python backslash", which in turn
leads to a mass of information. Just from the google search results
themselves, I see:
# first search result
2. Lexical analysis — Python v2.7.2 documentation
Python uses the 7-bit ASCII character set for program text. ... A
backslash does not continue a token except for string literals
# second search result
2.4.1 String literals
21 Feb 2008 – The backslash ( \ ) character is used to escape
characters ...
# third result
Python Gotchas
3 Jun 2008 – 2 "raw" strings and backslashes (when dealing with
Windows filenames). ...
The first one looks a bit technical (what on earth is lexical analysis?
-- look it up if you care) but the second and third look very promising.
Backslash is used to escape characters, and backslashes in Windows
filenames are a Gotcha.
And now you know how to catch fish :)
--
Steven
More information about the Tutor
mailing list