Reverse a string in Python

前端 未结 28 2500
南旧
南旧 2020-11-21 04:41

There is no built in reverse function for Python\'s str object. What is the best way of implementing this method?

If supplying a very conci

28条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 04:49

    Here is one without [::-1] or reversed (for learning purposes):

    def reverse(text):
        new_string = []
        n = len(text)
        while (n > 0):
            new_string.append(text[n-1])
            n -= 1
        return ''.join(new_string)
    print reverse("abcd")
    

    you can use += to concatenate strings but join() is faster.

提交回复
热议问题