2

I am trying to make a reverse function which takes an input (text) and outputs the reversed version. So "Polar" would print raloP.

def reverse(text):
    list = []
    text = str(text)
    x = len(text) - 1
    list.append("T" * x)
    for i in text:
        list.insert(x, i)
        x -= 1
    print "".join(list)

reverse("Something")
Community
  • 1
  • 1
Eric Leus
  • 57
  • 10
  • If you just need the functionality, consider the `reversed()` Python builtin. – immortal Aug 05 '17 at 11:14
  • 3
    There's a lot of misunderstanding in this code. The bit I'm most confused by is `list.append("T" * x)`. What is this supposed to do? – roganjosh Aug 05 '17 at 11:14
  • Slice your string, taking every character, and then set -1 as the step : `"Polar"[::-1]` gives what you want – Unatiel Aug 05 '17 at 11:15
  • 1
    Possible duplicate of [Reverse a string in Python](https://stackoverflow.com/questions/931092/reverse-a-string-in-python) – Joe Iddon Aug 05 '17 at 11:34

4 Answers4

6

As others have mentioned, Python already provides a couple of ways to reverse a string. The simple way is to use extended slicing: s[::-1] creates a reversed version of string s. Another way is to use the reversed function: ''.join(reversed(s)). But I guess it can be instructive to try implementing it for yourself.

There are several problems with your code.

Firstly,

list = []

You shouldn't use list as a variable name because that shadows the built-in list type. It won't hurt here, but it makes the code confusing, and if you did try to use list() later on in the function it would raise an exception with a cryptic error message.

text = str(text)

is redundant. text is already a string. str(text) returns the original string object, so it doesn't hurt anything, but it's still pointless.

x = len(text) - 1
list.append("T" * x)

You have an off-by-one error here. You really want to fill the list with as many items as are in the original string, this is short by one. Also, this code appends the string as a single item to the list, not as x separate items of one char each.

list.insert(x, i)

The .insert method inserts new items into a list, the subsequent items after the insertion point get moved up to make room. We don't want that, we just want to overwrite the current item at the x position, and we can do that by indexing.

When your code doesn't behave the way you expect it to, it's a Good Idea to add print statements at strategic places to make sure that variables have the value that they're supposed to have. That makes it much easier to find where things are going wrong.


Anyway, here's a repaired version of your code.

def reverse(text):
    lst = []
    x = len(text)
    lst.extend("T" * x)
    for i in text:
        x -= 1
        lst[x] = i
    print "".join(lst)

reverse("Something")

output

gnihtemoS

Here's an alternative approach, showing how to do it with .insert:

def reverse(text):
    lst = []
    for i in text:
        lst.insert(0, i)
    print "".join(lst)

Finally, instead of using a list we could use string concatenation. However, this approach is less efficient, especially with huge strings, but in modern versions of Python it's not as inefficient as it once was, as the str type has been optimised to handle this fairly common operation.

def reverse(text):
    s = ''
    for i in text:
        s = i + s
    print s

BTW, you really should be learning Python 3, Python 2 reaches its official End Of Life in 2020.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
  • This is the only answer the addresses the question (even if the question is only implied) – roganjosh Aug 05 '17 at 11:39
  • 1
    @roganjosh Thanks. It's all very well to say "Don't do it like that" and to show the OP better ways to do it, but it's also a bit frustrating when you want to understand why your algorithm doesn't behave the way you expect it to. – PM 2Ring Aug 05 '17 at 11:44
  • 1
    Exactly. You can see my comment on the top post trying to elicit detail like you have in your answer. I'm on a phone so I couldn't post it myself. "Teach a man to fish", and all that :) – roganjosh Aug 05 '17 at 11:45
  • @roganjosh Indeed, which is why I upvoted your comments. – PM 2Ring Aug 05 '17 at 11:48
  • 1
    @EricLues This answer explains in detail why your solution was wrong and how to fix it, you should read every single word of it – Mohd Aug 05 '17 at 12:28
4

You can try :

def reverse(text):
  return text[::-1]

print(reverse("Something")) # python 3
print reverse("Something") # python 2
Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45
  • 2
    Wow so simple, didn't know that that possible, thanks for info. – BladeMight Aug 05 '17 at 11:23
  • 1
    In this case, for the sake of OP, are you able to add some indication of why their code doesn't work? This does the job but it's radically different than their approach that has some serious misunderstanding behind it. – roganjosh Aug 05 '17 at 11:33
1

Easier way to do so:

def reverse(text):
  rev = ""
  i = len(text) - 1
  while i > -1:
    rev += text[i]
    i = i - 1
  return rev


print(reverse("Something"))

result: gnihtemoS

BladeMight
  • 2,670
  • 2
  • 21
  • 35
0

You could simply do

    print "something"[::-1]
yt.
  • 327
  • 1
  • 2
  • 11