Slice Notation?

Fredrik Lundh effbot at telia.com
Sun Oct 22 05:41:43 EDT 2000


Wynand van Dyk wrote:
> I am pretty new to python and I keep seeing ppl referring to "slice
> notation" which include a colon in square brackets somewhere in
> your code.
>
> I would like to know:
>
> 1) What exactly does it do?
> 2) What is it usefull for?
> 3) How would I use it in a program ie: example usage

the answers to your questions are all found in chapter 3
("An Informal Introduction to Python") of the standard
tutorial, available from:

http://www.python.org/doc/current/tut/tut.html

    "Strings can be subscripted (indexed); like in C, the
    first character of a string has subscript (index) 0.
    There is no separate character type; a character
    is simply a string of size one. Like in Icon, substrings
    can be specified with the slice notation: two indices
    separated by a colon.

        >>> word[4]
        'A'
        >>> word[0:2]
        'He'
        >>> word[2:4]
        'lp'

read the rest of that chapter to learn more about default
values, degenerate slices, how slices work with mutable
sequences, how to do slice assignments, etc.

then consider reading the entire tutorial ;-)

</F>





More information about the Python-list mailing list