0

Why isn't this functioning properly? I'm aware of the advanced slice ([::-1]) option but I would like to figure out how to reverse the str this way as well.

word = input("Please enter a word to reverse: ")

cut = len(word)
print(word[cut:-cut])
Zack
  • 661
  • 2
  • 11
  • 27

2 Answers2

2
word[cut:-cut]

May go from cut to -cut, which you could also write

word[cut:0]

but the step is still 1, which is still positive. So it will slice forward from the end, and stop because it's reached the end!

This implies that the step is needed either way, word[cut:-cut:-1]. When indexing backwards, both indexes need to reduced by one, so you have word[cut-1:-cut-1:-1], or word[cut-1:-6:-1], or even just word[::-1]. Note that -1 as the end parameter will be mangled back to the end of the string!

Veedrac
  • 58,273
  • 15
  • 112
  • 169
  • 2
    You'd have to use `word[cut-1:-1:-1]`, actually. – Martijn Pieters Sep 21 '13 at 19:01
  • 1
    @Martijn, nope, that doesn't work either. In slices, Python adds the length of the sequence to any negative index first. So your middle `-1` magically changes into `len(word) - 1`, and the slice is actually empty! Try it ;-) This just doesn't work the same way as the arguments to `range` or `xrange`. `word[cut-1::-1]` works (leave out the middle argument). – Tim Peters Sep 21 '13 at 19:06
  • @TimPeters: Argh, you are right, forgot about that corner case. No way to specify an end value of `-1` because negative values are overloaded.. – Martijn Pieters Sep 21 '13 at 19:07
  • @MartijnPieters, don't feel bad - I forget it several times each year - LOL ;-) – Tim Peters Sep 21 '13 at 19:08
0

Unless you specify a negative step, slices always go forwards. Specifying a start position after the end of the slice will only produce an empty slice. You need the negative step.

user2357112
  • 260,549
  • 28
  • 431
  • 505