Reverse really stuck


So i need to code that takes a string and print it backwards.

Got this error message:
Traceback (most recent call last):
File "", line 10, in
File "", line 7, in reverse
TypeError: Can't convert 'int' object to str implicitly

all i can get by myself that it's all about type of data.

So please, give me an slightly help, but not the full answer. Just want to really understand and not to just know the answer.

reverse_text="!gnirts desrever emoS"

def reverse(text):
	for i in text:
	return result


Hi, @kvizadsaderah ,

In this line, what is the value of key that you are attempting to concatenate to result? ...



So "result" is string, and "key" is a int.

tryied this


got result:


:slight_smile: :head_bandage:


Yes, key is an int. Specifically, you have arranged, here, for it to be an index of the text string ...


... but here you are converting that number directly to a string and concatenating that to result, instead of using it as an index in square brackets, so you wind up with a string of numbers ...


You can actually streamline your code by changing this ...

for i in text:

... to this ...

for i in range(len(text)):

... in order to establish i as an index. Then, you can get rid of the key variable entirely, and use the index, i, to access text, as follows ...

result = text[i] + result

Your loop would become ...

for i in range(len(text)):
    result = text[i] + result

That loop accesses each character in text in order from left to right, concatenating the character onto the left end of result.


Sure, but i need it backwards.
From right to left.
"abcd" to "dcba"


That's why you should concatenate in this order, as you access the text string from left to right ...

result = text[i] + result

However, if you prefer not to do it that way, you could redesign the loop in this manner instead ...


for i in range(len(text) -1, -1, -1):
    result += text[i]


Holy cow... I think i get this black magic with:


i just a slowpoke... ^_^ now i see it. Thank you.

Well, but got confused with you second example. :facepalm:

for i in range(len(text) -1, -1, -1):
result += text[i]


The second example accesses each character in text starting from the right side and proceeding to the left side, and as it finds each of those characters, it appends them to the right side of result. I believe that you were originally trying to do it that way.

See documentation for the range function.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.