string[i:j:k]

K

konstantin

Hello,
I'm not a newbie in python, but recently faced a problem in simple
expression:
some_string[i:j:k]
What does it mean? I believe this grammar (http://docs.python.org/ref/
slicings.html) describes the syntax. But I can't grasp it.
Thanks!
 
K

konstantin

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.
''
though I expected something like '8642'
What did i missed?
 
G

Gary Herron

konstantin said:
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
 
T

Terry Reedy

konstantin said:
Hello,
I'm not a newbie in python, but recently faced a problem in simple
expression:
some_string[i:j:k]
What does it mean? I believe this grammar (http://docs.python.org/ref/
slicings.html) describes the syntax. But I can't grasp it.

When you post a link, please put it on one line by itself, like this:
http://docs.python.org/ref/slicings.html
so it will be clickable as a whole by modern newsreaders.

Experimenting with bits of code in the interactive interpreter (or IDLE,
which is easier to cut from), like the responders did, is a great way to
learn.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
DewittMill
Top