No need to transform it to list


#1

Hey guys, (text) is originally set to be string, there is no need to transform it to list, or delete anything.
Here is my code

def reverse(text):
reverse = ""
for i in range(1, len(text)+1):
reverse += text[-i]
return reverse

It worked!!! Easy right?


7 Reverse -- curious
#2

I realise there's an element of self-learning expected in these tasks, however I would never have thought to look up slices because I never knew that existed until seeing these comments.

It specifically says not to use reverse slice: text[::-1] , but does it really expect us to delve into something we've never even heard of before?
I thought it would be possible along these lines:

while len(list1) > 0:
    list1.pop((len(list1))

but I can't manage tor return and append to list2.
I haven't seen this method anywhere; am I on the wrong track?


#3

After solving the exercise, I decided to see what other people had done. Since I'm haven't seen anything similar here, I would like to share what I have done and hope it helps.

def reverse(text):
txt = ''
for i in text:
txt = i + txt
return txt


#4

3 posts were split to a new topic: Some clarification to the use of the [-1] or [-i]


#7

The exercise specifically says not to use "reversed" command.


#8

This works because the string txt is being replaced with each iteration. It is a legitimate approach, but fails to treat a string as an immutable object. Somewhere down the line this type of approach could come with a gotcha.


#9

Now I remembered one of the previous lessons talking about treating strings as immutable objects, but I kind of got stuck and this was the only way I could figure it out. Should I be slicing the text when not using the reverse command or [::-1]? Thanks


#10

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