Reverse a string in Python

前端 未结 28 2472
南旧
南旧 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])
    
    0 讨论(0)
  • 2020-11-21 04:46

    A lesser perplexing way to look at it would be:

    string = 'happy'
    print(string)
    

    'happy'

    string_reversed = string[-1::-1]
    print(string_reversed)
    

    'yppah'

    In English [-1::-1] reads as:

    "Starting at -1, go all the way, taking steps of -1"

    0 讨论(0)
  • 2020-11-21 04:46
    s = 'hello'
    ln = len(s)
    i = 1
    while True:
        rev = s[ln-i]
        print rev,
        i = i + 1
        if i == ln + 1 :
            break
    

    OUTPUT :

    o l l e h
    
    0 讨论(0)
  • 2020-11-21 04:47
    def reverse(input):
        return reduce(lambda x,y : y+x, input)
    
    0 讨论(0)
  • 2020-11-21 04:49
    original = "string"
    
    rev_index = original[::-1]
    rev_func = list(reversed(list(original))) #nsfw
    
    print(original)
    print(rev_index)
    print(''.join(rev_func))
    
    0 讨论(0)
  • 2020-11-21 04:49

    Here is one without [::-1] or reversed (for learning purposes):

    def reverse(text):
        new_string = []
        n = len(text)
        while (n > 0):
            new_string.append(text[n-1])
            n -= 1
        return ''.join(new_string)
    print reverse("abcd")
    

    you can use += to concatenate strings but join() is faster.

    0 讨论(0)
提交回复
热议问题