On Fri, Jun 15, 2018 at 04:57:47PM +0300, kenneth yashim wrote:
> please im new to python or any other programming language. please i want to
> understand how slicing works
> 
>     [start,stop,step]
> 
> >>> 'abc'[0:3]
> 'abc'
> 
> >>>'abc'[0:-1]
> 'ab'
> 
> why does 'abc'[2:1]  or 'abc'[2:1] print ' ' instead of 'c'???

They don't return a space. They return an empty string, because the 
starting point comes AFTER the ending point.

The slice from 2 to 1 means:

- move to the right;
- start at position number two
- stop when you get to, or pass, position number one

Since you have already passed position number one, the slice stops 
collecting immediately, and you have an empty slice.

Slices cut the string at positions *between* the characters. If you have 
the string s="abcdef", imagine marking the gaps between the characters 
like this:

|a|b|c|d|e|f|

and numbering the gaps 0, 1, 2, 3, 4, 5, 6.

So the slice s[2:5] cuts at the gaps numbered 2 and 5:

|a|b||c|d|e||f|

giving you 'cde' as the returned slice.

If the ending position is to the left of the starting position, an 
empty slice is returned.


-- 
Steve
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to