0

I am new to python and I seem to be unable to understand the concept in Start:Stop:Step. For example

word = "Champ" print (word[0:5:2])

why do I get cap as I result ? if someone could help me with this I would truly appreciated

I tried using different numbers to see what the outcome was but even there I was not able to understand why was I getting that outcome

Rolf of Saxony
  • 21,661
  • 5
  • 39
  • 60

2 Answers2

1

Let's see this way:

word = "Champ"

print (word[0:5:2])
# you are taking index=0, then index=0+2, then index=0+2+2
# then index=0+2+2+2 (don't have this)
# so you got 0,2, and 4
# Hope, makes sense

print(word[0])
print(word[2])
print(word[4])
0

Maybe it's best to imagine it as a simple while-loop that creates an output. Take this example:

string = "Champ"
start = 0
stop = 5
step = 2

index = start
output = ""
while index < stop and index < len(string):
    output += string[index]
    index += step

print(output)
# >>> Cap

Here the current index starts at the start parameter, and then adds the current item to the output, then increments by the value step. If ever the current index is larger than the length of the original string, or larger than the stop value, the while-loop exits. Hope this helps!