Reverse a string in Python

前端 未结 28 2634
南旧
南旧 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条回答
  •  Happy的楠姐
    2020-11-21 05:05

    There are a lot of ways to reverse a string but I also created another one just for fun. I think this approach is not that bad.

    def reverse(_str):
        list_char = list(_str) # Create a hypothetical list. because string is immutable
    
        for i in range(len(list_char)/2): # just t(n/2) to reverse a big string
            list_char[i], list_char[-i - 1] = list_char[-i - 1], list_char[i]
    
        return ''.join(list_char)
    
    print(reverse("Ehsan"))
    

提交回复
热议问题