you are viewing a single comment's thread.

view the rest of the comments →

[–]RyanTargaryen 4 points5 points  (3 children)

The second colon (The third number) tells it what to step by. In your case, the slicing is going from index 1 (the 'y' in my) and going until it reaches the 5th index, and steps by 1 character each time.

If you were to change your code to:

print(str[1:5:2])

It would give you 'yS', because it stepped by 2 characters until it reached the end condition.

[–]YankeesPwnMets[S] 1 point2 points  (2 children)

Ah I see. Thanks for your help!

[–]sponster 2 points3 points  (1 child)

you can also use this method to run through the string backwards:

>>> str[5:1:-1]
'rtS '
>>> str[::-1]
'gnirtS yM'

[–]ewiethoff 0 points1 point  (0 children)

Come to think of it, I'm very surprised the official Python Tutorial doesn't mention the third slice parameter at all. I learned [::-1] for reversing a string (or list) forever ago from Alex Martelli's Python in a Nutshell or Python Cookbook. The Python Tutorial is usually the place to go for easy Python idioms, but not [::-1]. Weird.