Reverse a string in Python

前端 未结 28 2476
南旧
南旧 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

    Sure, in Python you can do very fancy 1-line stuff. :)
    Here's a simple, all rounder solution that could work in any programming language.

    def reverse_string(phrase):
        reversed = ""
        length = len(phrase)
        for i in range(length):
            reversed += phrase[length-1-i]
        return reversed
    
    phrase = raw_input("Provide a string: ")
    print reverse_string(phrase)
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2020-11-21 05:01

    @Paolo's s[::-1] is fastest; a slower approach (maybe more readable, but that's debatable) is ''.join(reversed(s)).

    0 讨论(0)
  • 2020-11-21 05:01

    This is simple and meaningful reverse function, easy to understand and code

    def reverse_sentence(text):
        words = text.split(" ")
        reverse =""
        for word in reversed(words):
            reverse += word+ " "
        return reverse
    
    0 讨论(0)
  • 2020-11-21 05:03

    Here is a no fancy one:

    def reverse(text):
        r_text = ''
        index = len(text) - 1
    
        while index >= 0:
            r_text += text[index] #string canbe concatenated
            index -= 1
    
        return r_text
    
    print reverse("hello, world!")
    
    0 讨论(0)
  • 2020-11-21 05:03

    Recursive method:

    def reverse(s): return s[0] if len(s)==1 else s[len(s)-1] + reverse(s[0:len(s)-1])
    

    example:

    print(reverse("Hello!"))    #!olleH
    
    0 讨论(0)
提交回复
热议问题