Reverse a string without using reversed() or [::-1]?

前端 未结 30 2621
南旧
南旧 2020-11-30 19:44

I came across a strange Codecademy exercise that required a function that would take a string as input and return it in reverse order. The only problem was you could not use

30条回答
  •  广开言路
    2020-11-30 19:55

    You've received a lot of alternative answers, but just to add another simple solution -- the first thing that came to mind something like this:

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

    It's not as fast as some of the other options people have mentioned(or built in methods), but easy to follow as we're simply using the length of the text string to concatenate one character at a time by slicing from the end toward the front.

提交回复
热议问题