MrBlubbintosh MrBlubbintosh - 1 month ago 13
Python Question

Slicing and skipping in Python

EDIT: I should be more clear. I really want to SKIP characters/letters, so not only solve the task of getting the first and last character to show. Even if I can do that by now. [::5] seems to work though.

I'm trying to slice a single word in python, so I'm given the first and the last letter. According to everything I read my code should be

word_ = "carrot"
letter = word_[0:6:4]
print(letter)


I understand it as the first 0 is the "c", the 6 is the "t" and the last 4 is how many characters you are skipping. The answer gives me "co". I have tried to experiment with my code but I only get the answer "co". Can someone explain to me what I'm doing wrong? I want the answer "ct"

Answer

Spaces included for readability.

word = "c a r r o t"
#       0 1 2 3 4 5
#         _
#           _
#             _
#               _
#                 _

The first character is indexed at 0, the last at 5.

So you'll take 5 steps to reach the last starting from the first. But if you're going to include the last character in the slice, the stop parameter of the slice has to be one place ahead; since the stop index is usually not included.

So your slice is [0:6:5] -> [start:stop:step]. There are sleeker ways to get the first and last index viz. [0] and [-1], or [::len(s)-1] but you can start with the former.


4 is not how many character you want to skip, but the number of steps required to reach the next character of your choice. And t will be located at 5 not 6