Newbie: Simple question about string slices

David Bolen db3l at fitlinxx.com
Fri Jun 9 01:34:30 EDT 2000


"Ray Smith" <Ray.Smith at fujitsu.com.au> writes:

> Hi there,
> 
> I'm completely new to Python and was reading the standard tutorial for
> Python and came across string slices., The tutorial says:

(...)

> "Here's a useful invariant of slice operations: s[:i] + s[i:]equals s."

(...)

> My question is:
> If given a slice s[a:b]
> can I assume index "b" means upto but not including the index "b"?

Precisely - that's required or else the invariant wouldn't be true.
It's also generally a very useful condition since it fits the base 0
addressing nicely, and helps simplify various computations of pieces
of strings and lists that otherwise would be adjusting computed
offsets by 1 a lot.

For one example, if a slice was inclusive then s[0:n] (or s[:n]) where
n was len(s) would have an upper bound one too large.

> I guess another way to ask my question is:
> Why is s[a:a] always '' (empty) ?

Because that particular slice doesn't cover a full element.  It's sort
of like a piece of the string just before the 'a'th element.  For
mutable objects (like lists) you can actually assign to a slice like
this to insert elements into the list at the point just before element
'a'.

> Hope someone out there in Python land can make sense of my question!

The tutorial you're reading does a reasonably good job of explaining
slices and providing examples, I think.  You might also peek at the
page just after the statement about the invariant that you mention
above also has a small ASCII diagram that provides one sample manner
of a way to think of slices (pointing between elements) that may also
help.

And as you've done, experimenting in the interactive interpreter is
one of the easiest ways to test out some of the language features.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list