Reverse a string in Python

前端 未结 28 2573
南旧
南旧 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:46

    1. using slice notation

    def rev_string(s): 
        return s[::-1]
    

    2. using reversed() function

    def rev_string(s): 
        return ''.join(reversed(s))
    

    3. using recursion

    def rev_string(s): 
        if len(s) == 1:
            return s
    
        return s[-1] + rev_string(s[:-1])
    

提交回复
热议问题