faqts : Computers : Programming : Languages : Python : Common Problems : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 7 people (57%) answered Yes
Recently 3 of 6 people (50%) answered Yes

Entry

If given a slice s[a:b] can I assume index "b" means upto but not including the index "b"?
Why is s[a:a] always '' (empty)?

Jun 10th, 2000 00:38
unknown unknown, Sean Blakey


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'.

Probably the easiest way to make sense of slice semantics is to think of
the slice indexes as counting the borders between values.  For example,
s[0:] is the slice from before the first character on. s[2:2] is the
"space" number two, which is between the elements of index 1 and two.

You have probably seen magic acts where a person is locked into a
segmented box.  The magician then places blades between the various
segments.

Think of a python sequence as being like this box.  Slice indexes do not
count the sub-boxes, but the spaces between the boxes where blades can
be inserted.  You can take your slice from above the head to just above
the ankles (body[0:-1]), or from the neck to below the feet (body[1:]),
or from the neck to the ankles (body[1:-1]).  If you insert two blades
at the neck (body[1:1]), you end up with nothing between them.

Slice indexes and direct indexes are different.  Perhaps it would help
to visualize your string like this:

0   1   2   3   4   5   6
| a | b | c | d | e | f |
  0   1   2   3   4   5

With this in mind, let's try to explain your examples:
s[2:2] == ''
The slice from separator 2 to separator two is a zero-length string.
This is the slice starting at the separator between 'b' and 'c', and
ending at the same place.

s[:2] + s[2:] == s      (a very nice feature of python, BTW)
Everything up to separator 2, plus everything after separator two.

In summary, and to actually get around to your question, s[:b] means up
to separator b, which is just before index b.  Similarly, s[b:] means
everything after separator b, which is just before index b.