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

前端 未结 30 2556
南旧
南旧 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

    Today I was asked this same exercise on pen&paper, so I come up with this function for lists:

    def rev(s):
      l = len(s)
      for i,j in zip(range(l-1, 0, -1), range(l//2)):
        s[i], s[j] = s[j], s[i]
      return s
    

    which can be used with strings with "".join(rev(list("hello")))

提交回复
热议问题