Reverse a string in Python

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

    Reverse a string without python magic.

    >>> def reversest(st):
        a=len(st)-1
        for i in st:
            print(st[a],end="")
            a=a-1
    
    0 讨论(0)
  • 2020-11-21 04:50

    You can use the reversed function with a list comprehesive. But I don't understand why this method was eliminated in python 3, was unnecessarily.

    string = [ char for char in reversed(string)]
    
    0 讨论(0)
  • 2020-11-21 04:53

    All of the above solutions are perfect but if we are trying to reverse a string using for loop in python will became a little bit tricky so here is how we can reverse a string using for loop

    string ="hello,world"
    for i in range(-1,-len(string)-1,-1):
        print (string[i],end=(" ")) 
    

    I hope this one will be helpful for someone.

    0 讨论(0)
  • 2020-11-21 04:54

    Thats my way:

    def reverse_string(string):
        character_list = []
        for char in string:
            character_list.append(char)
        reversed_string = ""
        for char in reversed(character_list):
            reversed_string += char
        return reversed_string
    
    0 讨论(0)
  • 2020-11-21 04:56

    Quick Answer (TL;DR)

    Example

    ### example01 -------------------
    mystring  =   'coup_ate_grouping'
    backwards =   mystring[::-1]
    print backwards
    
    ### ... or even ...
    mystring  =   'coup_ate_grouping'[::-1]
    print mystring
    
    ### result01 -------------------
    '''
    gnipuorg_eta_puoc
    '''
    

    Detailed Answer

    Background

    This answer is provided to address the following concern from @odigity:

    Wow. I was horrified at first by the solution Paolo proposed, but that took a back seat to the horror I felt upon reading the first comment: "That's very pythonic. Good job!" I'm so disturbed that such a bright community thinks using such cryptic methods for something so basic is a good idea. Why isn't it just s.reverse()?

    Problem

    • Context
      • Python 2.x
      • Python 3.x
    • Scenario:
      • Developer wants to transform a string
      • Transformation is to reverse order of all the characters

    Solution

    • example01 produces the desired result, using extended slice notation.

    Pitfalls

    • Developer might expect something like string.reverse()
    • The native idiomatic (aka "pythonic") solution may not be readable to newer developers
    • Developer may be tempted to implement his or her own version of string.reverse() to avoid slice notation.
    • The output of slice notation may be counter-intuitive in some cases:
      • see e.g., example02
        • print 'coup_ate_grouping'[-4:] ## => 'ping'
        • compared to
        • print 'coup_ate_grouping'[-4:-1] ## => 'pin'
        • compared to
        • print 'coup_ate_grouping'[-1] ## => 'g'
      • the different outcomes of indexing on [-1] may throw some developers off

    Rationale

    Python has a special circumstance to be aware of: a string is an iterable type.

    One rationale for excluding a string.reverse() method is to give python developers incentive to leverage the power of this special circumstance.

    In simplified terms, this simply means each individual character in a string can be easily operated on as a part of a sequential arrangement of elements, just like arrays in other programming languages.

    To understand how this works, reviewing example02 can provide a good overview.

    Example02

    ### example02 -------------------
    ## start (with positive integers)
    print 'coup_ate_grouping'[0]  ## => 'c'
    print 'coup_ate_grouping'[1]  ## => 'o' 
    print 'coup_ate_grouping'[2]  ## => 'u' 
    
    ## start (with negative integers)
    print 'coup_ate_grouping'[-1]  ## => 'g'
    print 'coup_ate_grouping'[-2]  ## => 'n' 
    print 'coup_ate_grouping'[-3]  ## => 'i' 
    
    ## start:end 
    print 'coup_ate_grouping'[0:4]    ## => 'coup'    
    print 'coup_ate_grouping'[4:8]    ## => '_ate'    
    print 'coup_ate_grouping'[8:12]   ## => '_gro'    
    
    ## start:end 
    print 'coup_ate_grouping'[-4:]    ## => 'ping' (counter-intuitive)
    print 'coup_ate_grouping'[-4:-1]  ## => 'pin'
    print 'coup_ate_grouping'[-4:-2]  ## => 'pi'
    print 'coup_ate_grouping'[-4:-3]  ## => 'p'
    print 'coup_ate_grouping'[-4:-4]  ## => ''
    print 'coup_ate_grouping'[0:-1]   ## => 'coup_ate_groupin'
    print 'coup_ate_grouping'[0:]     ## => 'coup_ate_grouping' (counter-intuitive)
    
    ## start:end:step (or start:end:stride)
    print 'coup_ate_grouping'[-1::1]  ## => 'g'   
    print 'coup_ate_grouping'[-1::-1] ## => 'gnipuorg_eta_puoc'
    
    ## combinations
    print 'coup_ate_grouping'[-1::-1][-4:] ## => 'puoc'
    

    Conclusion

    The cognitive load associated with understanding how slice notation works in python may indeed be too much for some adopters and developers who do not wish to invest much time in learning the language.

    Nevertheless, once the basic principles are understood, the power of this approach over fixed string manipulation methods can be quite favorable.

    For those who think otherwise, there are alternate approaches, such as lambda functions, iterators, or simple one-off function declarations.

    If desired, a developer can implement her own string.reverse() method, however it is good to understand the rationale behind this aspect of python.

    See also

    • alternate simple approach
    • alternate simple approach
    • alternate explanation of slice notation
    0 讨论(0)
  • 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.

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