[Tutor] still breaking chains
Steven D'Aprano
steve at pearwood.info
Mon Apr 13 03:11:52 CEST 2015
On Sun, Apr 12, 2015 at 11:03:07AM -0700, Jim Mooney wrote:
> If join returns a string, why am I getting a syntax error when I try to
> slice it?
Because you have a syntax error. Syntax error means you have written
something which the Python compiler cannot understand, because the
syntax is wrong, mangled or confused, or something is missing from the
line of code. (If the missing element is a closing bracket, brace or
parethesis, the compiler may not report the error until the line *after*
the offending line.) An English example:
"I would like a cup of coffee" -- correct syntax
"would coffee I cup like" -- syntax error
Human beings are more flexible with syntax and can sometimes decipher
rather mangled invalid sentences (e.g. most of us can understand Yoda)
but programming language compilers are less flexible and require you to
be pedantically correct:
+ 1 2 # syntax error
function(x y) # syntax error
'-'.join['a', 'b') # syntax error
This does not mean that Python cannot add numbers, call functions, or
join substrings. It means the compiler cannot understand my mangled
code. Fix the syntax:
1 + 2
function(x, y)
'-'.join(['a', 'b'])
In your example:
> >>> 'alfabeta'[2:5]
> 'fab'
> >>> ''.join(['a', 'l', 'f', 'a', 'b', 'e', 't', 'a')[2:5]
> SyntaxError: invalid syntax
I believe you have deleted what you might have thought was a blank line,
but actually gives you a hint as to what the error is. When I try to run
that, I get this:
py> ''.join(['a', 'l', 'f', 'a', 'b', 'e', 't', 'a')[2:5]
File "<stdin>", line 1
''.join(['a', 'l', 'f', 'a', 'b', 'e', 't', 'a')[2:5]
^
SyntaxError: invalid syntax
Look carefully at the "blank" line: it isn't actually blank. Way over on
the right hand side you will see a caret ^ pointing to the spot where
the compiler first noticed something it could not understand. In your
email, it may not line up, but in the interactive interpreter the caret
will line up with ) the closing round bracket. Why? Because before you
close the method call ''.join( ) you have to close the list [ ]:
''.join([...]) # okay
''.join([...) # syntax error
It is sad that the Python compiler does not report a more useful error
message here. It would be awesome if it would report:
SyntaxError: missing closing bracket ]
but we should count our blessing that we get anything at all.
--
Steve
More information about the Tutor
mailing list