[Tutor] Doubt!

Steven D'Aprano steve at pearwood.info
Wed Oct 24 01:36:29 CEST 2012

On 24/10/12 10:14, Nitin Ainani wrote:
> Dear Sir/Madam,
> I am  new to python I have a question. It is as follows:
> Suppose *s* is a variable and *s* stores empty string
> s=""
> Now if we write following statement
> print(s[0])      # it gives error
> print(s[0:])    # it does not give error
> why?

Because indexing a string returns the character at that index. If
the index is out-of-bounds, there is nothing to return and an
error will be raised:

py> s = "hello world"
py> s[0]
py> s[6]
py> s[100]
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
IndexError: string index out of range

The colon : tells Python to use a slice. Slices look like:


where step defaults to 1 if it is not given, start defaults to 0,
and end defaults to the length of the string.

py> s = "hello world"
py> s[0:5]
py> s[:5]
py> s[1:9]
'ello wor'

If either start or end is out of bounds, the result is truncated
at the ends of the string:

py> s[1:100]
'ello world'

If start is greater-or-equal to end, it is an empty slice, and
the empty string is returned:

py> s[6:3]

So the slice s[0:] says "give me the slice of the string s starting
at position 0 and extending up to the end of the string".

In the case of the empty string, since the string is empty, there
are no characters and every index is out-of-bounds. So s[0] will
raise an error. But the slice s[0:] is an empty slice, and will
return the empty string.

Slicing can be considered to be a short-cut for using a for-loop
and range.

s[start:end:step] is like this function:

def slice_copy(s, start, end=None, step=1):
     if end is None:
         end = len(s)
     new = []
     for i in range(start, end, step):
     return ''.join(new)

(except that real slicing can deal with out-of-bounds start and
end as well.)

If you study slice_copy, you should understand why an empty slice
returns the empty string.


More information about the Tutor mailing list