Reverse really stuck


#1


https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096

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

Got this error message:
Traceback (most recent call last):
File "rev_text2.py", line 10, in
reverse(reverse_text)
File "rev_text2.py", line 7, in reverse
result+=key
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):
	result=""
	key=len(text)-1
	for i in text:
		result+=key
		key-=1
	return result
reverse(reverse_text)


#2

Hi, @kvizadsaderah ,

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

result+=key

#3

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

tryied this

result+=str(key)

got result:

3938373635343332313029282726252423222120191817161514131211109876543210

:slight_smile: :head_bandage:


#4

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

key=len(text)-1

... 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 ...

result+=str(key):

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.


#5

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


#6

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]

#7

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

result=text[i]+result

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]


#8

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.


#9

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