2

In Python, I know I can reverse strings doing

'dfdfsdf'[::-1]

and that essentially makes it step backwards. However when I try to run this it won't work

string = 'dfdfsdf'
reversed = string[0:len(string):-1]
print(reversed)

I was just wondering doing this doesn't work; the format is [first:last:step], so I thought I could.

jscs
  • 63,694
  • 13
  • 151
  • 195
Sunisc
  • 23
  • 1
  • 5
  • 8
    You can't go from zero to a positive number striding by `-1` – Moses Koledoye Aug 30 '17 at 13:03
  • 1
    @khelwood That won't work. `-1` is still treated as the last character (not a number before `0`), so that returns an empty string. – Moses Koledoye Aug 30 '17 at 13:05
  • @Surya what exactly are you trying to do with reversed? – Mike - SMT Aug 30 '17 at 13:07
  • @SierraMountainTech Nothing. I program mostly in Java and just started learning Python. I was just wondering doing this doesn't work. Because the format is [first:last:step] so I thought I could. Could you explain it a bit more? – Sunisc Aug 30 '17 at 13:09
  • @Surya what is it that you thought you could do? There is no context. Are you trying to specify a stopping point when reversing? They way you can do that is by making the `last` portion a negative number. something like `reversed = string[:((-1)*len(string)):-1]` – Mike - SMT Aug 30 '17 at 13:11
  • `string[len(string)-1:-len(string)-1:-1]` See my explanation in the duplicate – Chris_Rands Aug 30 '17 at 13:12
  • 1
    I think Chris_Rands answer on the linked question will best describe the behavior. – Mike - SMT Aug 30 '17 at 13:16

1 Answers1

1

It doesn't work because iteration in list works like this:

list[start_point:end_point:iteration]

so for your method you need to write:

reversed = string[len(string)-1:-len(string)-1:-1]

more explained in dupe link

or you can achive reserved list/string using functions like this:

reversed = "".join(reversed(string))
  • 1
    Your last line should make it clear why you should avoid built-in names as variable names. You immediately shadow the class `reversed`, so the next call will fail: `reversed = "".join(reversed(string))` – Christian König Aug 30 '17 at 13:16
  • Your explanation is wrong, `string[len(string):0:-1] == string[::-1]` is `False`, as I commented `string[len(string)-1:-len(string)-1:-1]` see the dupe – Chris_Rands Aug 30 '17 at 13:24
  • If I do that then why do I have to iterate back by -1? Shouldn't I just use 1 since its going backwards either way? – Sunisc Aug 30 '17 at 13:25
  • Yep, i explained wrong. Because if you iterate to 0, it will exclude 0 index. Thanks for pointing it Chris. – Łukasz Szczesiak Aug 30 '17 at 13:41