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

前端 未结 30 2610
南旧
南旧 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:54

    You can simply reverse iterate your string starting from the last character. With python you can use list comprehension to construct the list of characters in reverse order and then join them to get the reversed string in a one-liner:

    def reverse(s):
      return "".join([s[-i-1] for i in xrange(len(s))])
    

    if you are not allowed to even use negative indexing you should replace s[-i-1] with s[len(s)-i-1]

提交回复
热议问题