string[i:j:k]

Gary Herron gherron at islandtraining.com
Tue Jul 22 02:25:10 EDT 2008


konstantin wrote:
> On Jul 22, 9:18 am, alex23 <wuwe... at gmail.com> wrote:
>   
>> On Jul 22, 3:10 pm, konstantin <konstantin.seliva... at gmail.com> wrote:
>>
>>     
>>> some_string[i:j:k]
>>> What does it mean?
>>>       
>> i = start position, j = end position, k = step size
>>
>>     
>>>>> s = "ABABABABABABAB"
>>>>> s[0:6:2]
>>>>>           
>> 'AAA'
>>     
>>>>> s = "ABCABCABCABCABC"
>>>>> s[0:6:3]
>>>>>           
>> 'AA'
>>
>> Hope this helps.
>>
>> - alex23
>>     
>
> Thanks!
> It seems that negative step leads in reverse direction.
> But logic isn't completely clear for me.
>   
>>>> s = '123456789'
>>>> s[::-2]
>>>>         
> '97531'
>
> but
>   
>>>> s[:-1:-2]
>>>>         

The slice s[:-1]
  means start at zero and go to n-1(where n-len(s))
  (it does not mean start at zero and go to -1)

So since the indexing is counting upward, the step size had better be 
positive.  Thus:
 >>> s = '123456789'
 >>> s[:-1:2]
'1357'
 >>>


Gary Herron



> ''
> though I expected something like '8642'
> What did i missed?
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>   




More information about the Python-list mailing list