Reverse a string in Python

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

    This is also an interesting way:

    def reverse_words_1(s):
        rev = ''
        for i in range(len(s)):
            j = ~i  # equivalent to j = -(i + 1)
            rev += s[j]
        return rev
    

    or similar:

    def reverse_words_2(s):
        rev = ''
        for i in reversed(range(len(s)):
            rev += s[i]
        return rev
    

    Another more 'exotic' way using byterarray which supports .reverse()

    b = bytearray('Reverse this!', 'UTF-8')
    b.reverse()
    b.decode('UTF-8')
    

    will produce:

    '!siht esreveR'
    

提交回复
热议问题