Reverse a string in Python

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

提交回复
热议问题