0

While doing a homework question, forgetting that that there is a built-in reverse function for strings, I came up with my own way of reversing strings.

So here it is:

for i in range(len(string)):
    reversed = string[i] + reversed

I was wondering if this is an efficient (say, if I have a really long string) and correct way of reversing.

  • 1
    *"correct way of reversing?"* - considering that there's a much simpler native way I'd say *no*. In terms of "does it work", you can judge for yourself. – deceze Apr 05 '17 at 14:19
  • If you have curiosity you could study the source code of the build in function – daniel_hck Apr 05 '17 at 14:19
  • I'd say in SO this is a dupe as @Keiwan pointed out. OTOH, it sounds like you're asking for code review, so it might better belong on [that site](https://codereview.stackexchange.com). – kojiro Apr 05 '17 at 14:20
  • The fastest way is [::-1] : https://hastebin.com/vovapavoyu.py – Neil Apr 05 '17 at 14:23
  • If you want to study a non standard way of reversing a string, study [recursion](http://stackoverflow.com/a/5532914/298607) – dawg Apr 05 '17 at 14:24
  • As far as efficiency of your example is concerned: No, it's definitely not efficient. Python strings are immutable so you should never concatenate them using `+` if you care about performance. Either use `[::-1]` or an approach using the `join` function (which is slower than `[::.-1]` but still a lot faster than your version) – Keiwan Apr 05 '17 at 14:57
  • I have actually seen the duplicated link but it doesn't really answer my question, so I posted a new one. – Michael Apr 06 '17 at 05:44

2 Answers2

0

You could compare the timing. It's probably quite inefficient, because you make a new string object on every loop iteration and you loop through each character in the string in a Python loop. The built-in function however uses native C code (CPython).

CodeMonkey
  • 4,067
  • 1
  • 31
  • 43
0

There's a one-liner: reversed = string[::-1]

However, it's kind of hard to read unless you already know the syntax. So you could always bury it in a function with a more helpful name:

def reverse(string):
    return string[::-1]
Ben Quigley
  • 727
  • 4
  • 18