Reverse a string in Python

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

    def reverse_string(string):
        length = len(string)
        temp = ''
        for i in range(length):
            temp += string[length - i - 1]
        return temp
    
    print(reverse_string('foo')) #prints "oof"
    

    This works by looping through a string and assigning its values in reverse order to another string.

提交回复
热议问题