Reverse a string in Python

前端 未结 28 2566
南旧
南旧 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 05:03
     a=input()
     print(a[::-1])
    

    The above code recieves the input from the user and prints an output that is equal to the reverse of the input by adding [::-1].

    OUTPUT:

    >>> Happy 
    >>> yppaH
    

    But when it comes to the case of sentences, view the code output below:

    >>> Have a happy day
    >>> yad yppah a evaH
    

    But if you want only the characters of the string to be reversed and not the sequence of string, try this:

    a=input().split() #Splits the input on the basis of space (" ")
    for b in a: #declares that var (b) is any value in the list (a)
        print(b[::-1], end=" ") #End declares to print the character in its quotes (" ") without a new line.
    

    In the above code in line 2 in I said that ** variable b is any value in the list (a)** I said var a to be a list because when you use split in an input the variable of the input becomes a list. Also remember that split can't be used in the case of int(input())

    OUTPUT:

    >>> Have a happy day
    >>> evaH a yppah yad
    

    If we don't add end(" ") in the above code then it will print like the following:

    >>> Have a happy day
    >>> evaH
    >>> a
    >>> yppah
    >>> yad
    

    Below is an example to understand end():

    CODE:

    for i in range(1,6):
         print(i) #Without end()
    

    OUTPUT:

    >>> 1
    >>> 2
    >>> 3
    >>> 4
    >>> 5
    

    Now code with end():

    for i in range(1,6):
        print(i, end=" || ")
    

    OUTPUT:

    >>> 1 || 2 || 3 || 4 || 5 ||
    
    0 讨论(0)
  • 2020-11-21 05:03

    With python 3 you can reverse the string in-place meaning it won't get assigned to another variable. First you have to convert the string into a list and then leverage the reverse() function.

    https://docs.python.org/3/tutorial/datastructures.html

       def main():
            my_string = ["h","e","l","l","o"]
            print(reverseString(my_string))
    
        def reverseString(s):
          print(s)
          s.reverse()
          return s
    
        if __name__ == "__main__":
            main()
    
    0 讨论(0)
  • 2020-11-21 05:05

    How about:

    >>> 'hello world'[::-1]
    'dlrow olleh'
    

    This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string.

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

    There are a lot of ways to reverse a string but I also created another one just for fun. I think this approach is not that bad.

    def reverse(_str):
        list_char = list(_str) # Create a hypothetical list. because string is immutable
    
        for i in range(len(list_char)/2): # just t(n/2) to reverse a big string
            list_char[i], list_char[-i - 1] = list_char[-i - 1], list_char[i]
    
        return ''.join(list_char)
    
    print(reverse("Ehsan"))
    
    0 讨论(0)
  • 2020-11-21 05:06

    What is the best way of implementing a reverse function for strings?

    My own experience with this question is academic. However, if you're a pro looking for the quick answer, use a slice that steps by -1:

    >>> 'a string'[::-1]
    'gnirts a'
    

    or more readably (but slower due to the method name lookups and the fact that join forms a list when given an iterator), str.join:

    >>> ''.join(reversed('a string'))
    'gnirts a'
    

    or for readability and reusability, put the slice in a function

    def reversed_string(a_string):
        return a_string[::-1]
    

    and then:

    >>> reversed_string('a_string')
    'gnirts_a'
    

    Longer explanation

    If you're interested in the academic exposition, please keep reading.

    There is no built-in reverse function in Python's str object.

    Here is a couple of things about Python's strings you should know:

    1. In Python, strings are immutable. Changing a string does not modify the string. It creates a new one.

    2. Strings are sliceable. Slicing a string gives you a new string from one point in the string, backwards or forwards, to another point, by given increments. They take slice notation or a slice object in a subscript:

      string[subscript]
      

    The subscript creates a slice by including a colon within the braces:

        string[start:stop:step]
    

    To create a slice outside of the braces, you'll need to create a slice object:

        slice_obj = slice(start, stop, step)
        string[slice_obj]
    

    A readable approach:

    While ''.join(reversed('foo')) is readable, it requires calling a string method, str.join, on another called function, which can be rather relatively slow. Let's put this in a function - we'll come back to it:

    def reverse_string_readable_answer(string):
        return ''.join(reversed(string))
    

    Most performant approach:

    Much faster is using a reverse slice:

    'foo'[::-1]
    

    But how can we make this more readable and understandable to someone less familiar with slices or the intent of the original author? Let's create a slice object outside of the subscript notation, give it a descriptive name, and pass it to the subscript notation.

    start = stop = None
    step = -1
    reverse_slice = slice(start, stop, step)
    'foo'[reverse_slice]
    

    Implement as Function

    To actually implement this as a function, I think it is semantically clear enough to simply use a descriptive name:

    def reversed_string(a_string):
        return a_string[::-1]
    

    And usage is simply:

    reversed_string('foo')
    

    What your teacher probably wants:

    If you have an instructor, they probably want you to start with an empty string, and build up a new string from the old one. You can do this with pure syntax and literals using a while loop:

    def reverse_a_string_slowly(a_string):
        new_string = ''
        index = len(a_string)
        while index:
            index -= 1                    # index = index - 1
            new_string += a_string[index] # new_string = new_string + character
        return new_string
    

    This is theoretically bad because, remember, strings are immutable - so every time where it looks like you're appending a character onto your new_string, it's theoretically creating a new string every time! However, CPython knows how to optimize this in certain cases, of which this trivial case is one.

    Best Practice

    Theoretically better is to collect your substrings in a list, and join them later:

    def reverse_a_string_more_slowly(a_string):
        new_strings = []
        index = len(a_string)
        while index:
            index -= 1                       
            new_strings.append(a_string[index])
        return ''.join(new_strings)
    

    However, as we will see in the timings below for CPython, this actually takes longer, because CPython can optimize the string concatenation.

    Timings

    Here are the timings:

    >>> a_string = 'amanaplanacanalpanama' * 10
    >>> min(timeit.repeat(lambda: reverse_string_readable_answer(a_string)))
    10.38789987564087
    >>> min(timeit.repeat(lambda: reversed_string(a_string)))
    0.6622700691223145
    >>> min(timeit.repeat(lambda: reverse_a_string_slowly(a_string)))
    25.756799936294556
    >>> min(timeit.repeat(lambda: reverse_a_string_more_slowly(a_string)))
    38.73570013046265
    

    CPython optimizes string concatenation, whereas other implementations may not:

    ... do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

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

    Here is simply:

    print "loremipsum"[-1::-1]

    and some logically:

    def str_reverse_fun():
        empty_list = []
        new_str = 'loremipsum'
        index = len(new_str)
        while index:
            index = index - 1
            empty_list.append(new_str[index])
        return ''.join(empty_list)
    print str_reverse_fun()
    

    output:

    muspimerol

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