[Tutor] still breaking chains

Ben Finney ben+python at benfinney.id.au
Mon Apr 13 01:47:17 CEST 2015


Jim Mooney <cybervigilante at gmail.com> writes:

> If join returns a string, why am I getting a syntax error when I try  to
> slice it?
>
> >>> 'alfabeta'[2:5]
> 'fab'
> >>> ''.join(['a', 'l', 'f', 'a', 'b', 'e', 't', 'a')[2:5]
> SyntaxError: invalid syntax

This demonstrates the primary problem with so-called “chaining”. Your
statement is too complex, and you have misunderstood where in that
statement the error is.

Break the statement into at least two: get the result of the ‘join’, and
then in the next statement slice that value. You'll see where the error
was.

One important principle to follow is to write your statements to be very
simple, so that when something goes wrong it is as easy as possible to
read the statement and understand what it *actually* says.

Chaining long strings of operations together in a single statement goes
directly against that principle, and hence is to be avoided.

-- 
 \       “[T]he speed of response of the internet will re-introduce us |
  `\    to that from which our political systems have separated us for |
_o__)    so long, the consequences of our own actions.” —Douglas Adams |
Ben Finney



More information about the Tutor mailing list