0

Refer to the CODE and OUTPUT below. There is no OUTPUT for the third print statement. An altered print statement in its place such as print(long_word[3:7]) gives output (elin).

# [ ] print the first 4 letters of long_word
# [ ] print the first 4 letters of long_word in reverse
# [ ] print the last 4 letters of long_word in reverse
# [ ] print the letters spanning indexes 3 to 6 of long_word in Reverse
long_word = "timeline"
print(long_word[:4])
print(long_word[3::-1])
print(long_word[3:7:-1])
print(long_word[-1:-5:-1])

OUTPUT

time
emit

enil

What gives? The situation of this question also raised in link below. It is unaddressed as of now.

4 Answers 4

1

The slice operation in Python is [start:end:step], when step=-1, it represents get values in the reverse direction.

So when use print(long_word[3::-1]), it is actually from index 3 to index 0 which is determined by reverse direction flag step=-1. But when use print(long_word[3:7:-1]), it represents from index 3 to index 7 which is not a reverse order and it is a collision.

Sign up to request clarification or add additional context in comments.

2 Comments

Right, so it should be print(long_word[6:2:-1]) This works. One would expect an error in the above case of collision, no?
I think it is not an error, as you can use print(long_word[2:15]) or print(long_word[3:1]). It is just not a rational range.
0

If you want to print last four letters in reverse try the below code:

long_word = "Characteristics" 

print(long_word[14:10:-1])     

Result: scit

14 is a starting string index
10 is an ending string index
-1 is used to reverse the string one by one

Comments

0
long_word = "timeline"

print(long_word[0:4])

print(long_word[3::-1])

print(long_word[-1:3:-1])

print(long_word[-3:-7:-1])

This is what I have tried, I think it is an answer of your question.

Comments

0

The correct code is:

    long_word = "timeline"
    print(long_word[:4])
    print(long_word[3::-1]) 
    print(long_word[-1:-5:-1])
    print(long_word[6:2:-1])

time
emit
enil
nile

Note that when reversing, you state the wanted ending index first, then the wanted start index - 1 second(except for the 0 index do not subtract one from it), like so:

long_word(wanted ending index: wanted start index - 1: -1)

1 Comment

Can you highlight the neccessary changes?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.