Reverse a string in Python












1195















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 concise answer, please elaborate on its efficiency. For example, whether the str object is converted to a different object, etc.










share|improve this question





























    1195















    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 concise answer, please elaborate on its efficiency. For example, whether the str object is converted to a different object, etc.










    share|improve this question



























      1195












      1195








      1195


      364






      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 concise answer, please elaborate on its efficiency. For example, whether the str object is converted to a different object, etc.










      share|improve this question
















      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 concise answer, please elaborate on its efficiency. For example, whether the str object is converted to a different object, etc.







      python string






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 6 '17 at 9:18









      Alex Riley

      80.9k26160165




      80.9k26160165










      asked May 31 '09 at 2:10









      oneselfoneself

      14k2673108




      14k2673108
























          23 Answers
          23






          active

          oldest

          votes


















          2430














          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.






          share|improve this answer





















          • 22





            That doesn't work for utf8 though .. I needed to do this as well b = a.decode('utf8')[::-1].encode('utf8') but thanks for the right direction !

            – Ricky Levi
            Apr 22 '17 at 15:18






          • 6





            @RickyLevi If .decode('utf8') is required, it means a does not contain any string objects, rather bytes.

            – Shiplu Mokaddim
            Nov 1 '17 at 18:43





















          236














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






          share|improve this answer





















          • 7





            This is about 3 times slower.

            – oneself
            Oct 6 '17 at 15:09








          • 2





            And a quick comment to say what it does will explain it better than using this slower version!

            – tburrows13
            Nov 2 '17 at 22:04






          • 3





            it's slower because join has to build the list anyway to be able to get the size. ''.join(list(reversed(s))) may be slightly faster.

            – Jean-François Fabre
            Dec 11 '17 at 21:34



















          188















          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.







          share|improve this answer

































            34














            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






            share|improve this answer

































              10














              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"







              share|improve this answer































                6














                using slice notation



                def rev_string(s): 
                return s[::-1]


                using reversed() function



                def rev_string(s): 
                return ''.join(reversed(s))


                using recursion



                def rev_string(s): 
                if len(s) == 1:
                return s

                return s[-1] + rev_string(s[:-1])





                share|improve this answer
























                • Gotta watch the recursion solution, if the string is decent length you'll run into RecursionError: maximum recursion depth exceeded while calling a Python object. Ex: rev_string("abcdef"*1000)

                  – Adam Parkin
                  Feb 21 at 16:47



















                5














                Reverse a string in python without using reversed() or [::-1]



                def reverse(test):
                n = len(test)
                x=""
                for i in range(n-1,-1,-1):
                x += test[i]
                return x





                share|improve this answer



















                • 1





                  Shouldn't you use xrange since you don't need the list, in python 2?

                  – UnitasBrooks
                  May 24 '18 at 15:32



















                3














                def reverse(input):
                return reduce(lambda x,y : y+x, input)





                share|improve this answer





















                • 2





                  I clicked upvote, because I like this lambda expression. Unfortunately, it's the least efficient solution from all listed above (test: Gist palindrome.py )

                  – oski86
                  Jul 24 '15 at 16:32



















                3














                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 = byterarray('Reverse this!', 'UTF-8')
                b.reverse()
                b.decode('UTF-8')`


                will produce:



                '!siht esreveR'





                share|improve this answer

































                  1














                  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!")





                  share|improve this answer































                    1














                    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.






                    share|improve this answer

































                      1














                      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





                      share|improve this answer































                        1














                        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.






                        share|improve this answer































                          1














                          original = "string"

                          rev_index = original[::-1]
                          rev_func = list(reversed(list(original))) #nsfw

                          print(original)
                          print(rev_index)
                          print(''.join(rev_func))





                          share|improve this answer
























                          • While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context.

                            – Robert Columbia
                            Dec 29 '18 at 11:11



















                          0














                          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.






                          share|improve this answer































                            0














                            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





                            share|improve this answer































                              0














                              Do not know about the efficiency but a short solution found on the MIT lectures is



                              s = "abcd"

                              s[-1:-(len(s)+1):-1]
                              Out[5]: 'dcba'


                              You may read more about Slices to get a better understanding of this code.






                              share|improve this answer


























                              • Why would you include the start & stop, if the goal is to just reverse the string?

                                – Adam Parkin
                                Feb 21 at 16:34











                              • @Adam This one I got from MIT lectures. Not created by me.

                                – Krishnadas PC
                                Feb 21 at 17:15



















                              -1














                              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






                              share|improve this answer































                                -1














                                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





                                share|improve this answer
























                                • While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.

                                  – hellow
                                  Nov 11 '18 at 7:21



















                                -2














                                s = 'Hello world'



                                s[::-1]



                                in the above example label s or variable s is holding string which contain Hello world string and on second step i m printing reverse of Hello world string by taking starting from everything to everything in reverse step order with -1.






                                share|improve this answer































                                  -4














                                  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)





                                  share|improve this answer



















                                  • 1





                                    It is not a nice solution to have such a long code for such a trivial task.

                                    – Hunter_71
                                    Oct 9 '17 at 23:14



















                                  -4














                                  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





                                  share|improve this answer





















                                  • 1





                                    what is the point of using a while loop here?

                                    – AsheKetchum
                                    Mar 29 '17 at 15:18



















                                  -5














                                  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)]





                                  share|improve this answer



















                                  • 1





                                    What was eliminated? This continues to work just fine in Py3...

                                    – ShadowRanger
                                    Nov 4 '16 at 5:54











                                  • The question asks for the reverse of a string, and you instead give a list??

                                    – user21820
                                    Feb 25 '17 at 13:47











                                  • you need a .join or something to make it a valid answer

                                    – AsheKetchum
                                    Mar 29 '17 at 15:17











                                  • BTW, [c for c in string] is tantamount to list(string).

                                    – Right leg
                                    Sep 8 '17 at 12:02










                                  protected by Jon Clements Apr 11 '13 at 8:29



                                  Thank you for your interest in this question.
                                  Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                  Would you like to answer one of these unanswered questions instead?














                                  23 Answers
                                  23






                                  active

                                  oldest

                                  votes








                                  23 Answers
                                  23






                                  active

                                  oldest

                                  votes









                                  active

                                  oldest

                                  votes






                                  active

                                  oldest

                                  votes









                                  2430














                                  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.






                                  share|improve this answer





















                                  • 22





                                    That doesn't work for utf8 though .. I needed to do this as well b = a.decode('utf8')[::-1].encode('utf8') but thanks for the right direction !

                                    – Ricky Levi
                                    Apr 22 '17 at 15:18






                                  • 6





                                    @RickyLevi If .decode('utf8') is required, it means a does not contain any string objects, rather bytes.

                                    – Shiplu Mokaddim
                                    Nov 1 '17 at 18:43


















                                  2430














                                  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.






                                  share|improve this answer





















                                  • 22





                                    That doesn't work for utf8 though .. I needed to do this as well b = a.decode('utf8')[::-1].encode('utf8') but thanks for the right direction !

                                    – Ricky Levi
                                    Apr 22 '17 at 15:18






                                  • 6





                                    @RickyLevi If .decode('utf8') is required, it means a does not contain any string objects, rather bytes.

                                    – Shiplu Mokaddim
                                    Nov 1 '17 at 18:43
















                                  2430












                                  2430








                                  2430







                                  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.






                                  share|improve this answer















                                  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.







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Feb 25 '14 at 2:13









                                  Mokolodi1

                                  7910




                                  7910










                                  answered May 31 '09 at 2:11









                                  Paolo BergantinoPaolo Bergantino

                                  381k73491426




                                  381k73491426








                                  • 22





                                    That doesn't work for utf8 though .. I needed to do this as well b = a.decode('utf8')[::-1].encode('utf8') but thanks for the right direction !

                                    – Ricky Levi
                                    Apr 22 '17 at 15:18






                                  • 6





                                    @RickyLevi If .decode('utf8') is required, it means a does not contain any string objects, rather bytes.

                                    – Shiplu Mokaddim
                                    Nov 1 '17 at 18:43
















                                  • 22





                                    That doesn't work for utf8 though .. I needed to do this as well b = a.decode('utf8')[::-1].encode('utf8') but thanks for the right direction !

                                    – Ricky Levi
                                    Apr 22 '17 at 15:18






                                  • 6





                                    @RickyLevi If .decode('utf8') is required, it means a does not contain any string objects, rather bytes.

                                    – Shiplu Mokaddim
                                    Nov 1 '17 at 18:43










                                  22




                                  22





                                  That doesn't work for utf8 though .. I needed to do this as well b = a.decode('utf8')[::-1].encode('utf8') but thanks for the right direction !

                                  – Ricky Levi
                                  Apr 22 '17 at 15:18





                                  That doesn't work for utf8 though .. I needed to do this as well b = a.decode('utf8')[::-1].encode('utf8') but thanks for the right direction !

                                  – Ricky Levi
                                  Apr 22 '17 at 15:18




                                  6




                                  6





                                  @RickyLevi If .decode('utf8') is required, it means a does not contain any string objects, rather bytes.

                                  – Shiplu Mokaddim
                                  Nov 1 '17 at 18:43







                                  @RickyLevi If .decode('utf8') is required, it means a does not contain any string objects, rather bytes.

                                  – Shiplu Mokaddim
                                  Nov 1 '17 at 18:43















                                  236














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






                                  share|improve this answer





















                                  • 7





                                    This is about 3 times slower.

                                    – oneself
                                    Oct 6 '17 at 15:09








                                  • 2





                                    And a quick comment to say what it does will explain it better than using this slower version!

                                    – tburrows13
                                    Nov 2 '17 at 22:04






                                  • 3





                                    it's slower because join has to build the list anyway to be able to get the size. ''.join(list(reversed(s))) may be slightly faster.

                                    – Jean-François Fabre
                                    Dec 11 '17 at 21:34
















                                  236














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






                                  share|improve this answer





















                                  • 7





                                    This is about 3 times slower.

                                    – oneself
                                    Oct 6 '17 at 15:09








                                  • 2





                                    And a quick comment to say what it does will explain it better than using this slower version!

                                    – tburrows13
                                    Nov 2 '17 at 22:04






                                  • 3





                                    it's slower because join has to build the list anyway to be able to get the size. ''.join(list(reversed(s))) may be slightly faster.

                                    – Jean-François Fabre
                                    Dec 11 '17 at 21:34














                                  236












                                  236








                                  236







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






                                  share|improve this answer















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







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Nov 29 '14 at 18:28









                                  zadrozny

                                  3931619




                                  3931619










                                  answered May 31 '09 at 2:13









                                  Alex MartelliAlex Martelli

                                  629k12810401280




                                  629k12810401280








                                  • 7





                                    This is about 3 times slower.

                                    – oneself
                                    Oct 6 '17 at 15:09








                                  • 2





                                    And a quick comment to say what it does will explain it better than using this slower version!

                                    – tburrows13
                                    Nov 2 '17 at 22:04






                                  • 3





                                    it's slower because join has to build the list anyway to be able to get the size. ''.join(list(reversed(s))) may be slightly faster.

                                    – Jean-François Fabre
                                    Dec 11 '17 at 21:34














                                  • 7





                                    This is about 3 times slower.

                                    – oneself
                                    Oct 6 '17 at 15:09








                                  • 2





                                    And a quick comment to say what it does will explain it better than using this slower version!

                                    – tburrows13
                                    Nov 2 '17 at 22:04






                                  • 3





                                    it's slower because join has to build the list anyway to be able to get the size. ''.join(list(reversed(s))) may be slightly faster.

                                    – Jean-François Fabre
                                    Dec 11 '17 at 21:34








                                  7




                                  7





                                  This is about 3 times slower.

                                  – oneself
                                  Oct 6 '17 at 15:09







                                  This is about 3 times slower.

                                  – oneself
                                  Oct 6 '17 at 15:09






                                  2




                                  2





                                  And a quick comment to say what it does will explain it better than using this slower version!

                                  – tburrows13
                                  Nov 2 '17 at 22:04





                                  And a quick comment to say what it does will explain it better than using this slower version!

                                  – tburrows13
                                  Nov 2 '17 at 22:04




                                  3




                                  3





                                  it's slower because join has to build the list anyway to be able to get the size. ''.join(list(reversed(s))) may be slightly faster.

                                  – Jean-François Fabre
                                  Dec 11 '17 at 21:34





                                  it's slower because join has to build the list anyway to be able to get the size. ''.join(list(reversed(s))) may be slightly faster.

                                  – Jean-François Fabre
                                  Dec 11 '17 at 21:34











                                  188















                                  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.







                                  share|improve this answer






























                                    188















                                    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.







                                    share|improve this answer




























                                      188












                                      188








                                      188








                                      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.







                                      share|improve this answer
















                                      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.








                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Sep 27 '17 at 16:14

























                                      answered Jan 8 '15 at 15:32









                                      Aaron HallAaron Hall

                                      177k51305255




                                      177k51305255























                                          34














                                          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






                                          share|improve this answer






























                                            34














                                            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






                                            share|improve this answer




























                                              34












                                              34








                                              34







                                              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






                                              share|improve this answer















                                              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







                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Apr 16 '18 at 17:42

























                                              answered Oct 31 '15 at 22:24









                                              dreftymacdreftymac

                                              16k2190153




                                              16k2190153























                                                  10














                                                  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"







                                                  share|improve this answer




























                                                    10














                                                    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"







                                                    share|improve this answer


























                                                      10












                                                      10








                                                      10







                                                      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"







                                                      share|improve this answer













                                                      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"








                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered Apr 1 '16 at 7:49









                                                      pX0rpX0r

                                                      65069




                                                      65069























                                                          6














                                                          using slice notation



                                                          def rev_string(s): 
                                                          return s[::-1]


                                                          using reversed() function



                                                          def rev_string(s): 
                                                          return ''.join(reversed(s))


                                                          using recursion



                                                          def rev_string(s): 
                                                          if len(s) == 1:
                                                          return s

                                                          return s[-1] + rev_string(s[:-1])





                                                          share|improve this answer
























                                                          • Gotta watch the recursion solution, if the string is decent length you'll run into RecursionError: maximum recursion depth exceeded while calling a Python object. Ex: rev_string("abcdef"*1000)

                                                            – Adam Parkin
                                                            Feb 21 at 16:47
















                                                          6














                                                          using slice notation



                                                          def rev_string(s): 
                                                          return s[::-1]


                                                          using reversed() function



                                                          def rev_string(s): 
                                                          return ''.join(reversed(s))


                                                          using recursion



                                                          def rev_string(s): 
                                                          if len(s) == 1:
                                                          return s

                                                          return s[-1] + rev_string(s[:-1])





                                                          share|improve this answer
























                                                          • Gotta watch the recursion solution, if the string is decent length you'll run into RecursionError: maximum recursion depth exceeded while calling a Python object. Ex: rev_string("abcdef"*1000)

                                                            – Adam Parkin
                                                            Feb 21 at 16:47














                                                          6












                                                          6








                                                          6







                                                          using slice notation



                                                          def rev_string(s): 
                                                          return s[::-1]


                                                          using reversed() function



                                                          def rev_string(s): 
                                                          return ''.join(reversed(s))


                                                          using recursion



                                                          def rev_string(s): 
                                                          if len(s) == 1:
                                                          return s

                                                          return s[-1] + rev_string(s[:-1])





                                                          share|improve this answer













                                                          using slice notation



                                                          def rev_string(s): 
                                                          return s[::-1]


                                                          using reversed() function



                                                          def rev_string(s): 
                                                          return ''.join(reversed(s))


                                                          using recursion



                                                          def rev_string(s): 
                                                          if len(s) == 1:
                                                          return s

                                                          return s[-1] + rev_string(s[:-1])






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered May 20 '18 at 22:24









                                                          harryharry

                                                          135115




                                                          135115













                                                          • Gotta watch the recursion solution, if the string is decent length you'll run into RecursionError: maximum recursion depth exceeded while calling a Python object. Ex: rev_string("abcdef"*1000)

                                                            – Adam Parkin
                                                            Feb 21 at 16:47



















                                                          • Gotta watch the recursion solution, if the string is decent length you'll run into RecursionError: maximum recursion depth exceeded while calling a Python object. Ex: rev_string("abcdef"*1000)

                                                            – Adam Parkin
                                                            Feb 21 at 16:47

















                                                          Gotta watch the recursion solution, if the string is decent length you'll run into RecursionError: maximum recursion depth exceeded while calling a Python object. Ex: rev_string("abcdef"*1000)

                                                          – Adam Parkin
                                                          Feb 21 at 16:47





                                                          Gotta watch the recursion solution, if the string is decent length you'll run into RecursionError: maximum recursion depth exceeded while calling a Python object. Ex: rev_string("abcdef"*1000)

                                                          – Adam Parkin
                                                          Feb 21 at 16:47











                                                          5














                                                          Reverse a string in python without using reversed() or [::-1]



                                                          def reverse(test):
                                                          n = len(test)
                                                          x=""
                                                          for i in range(n-1,-1,-1):
                                                          x += test[i]
                                                          return x





                                                          share|improve this answer



















                                                          • 1





                                                            Shouldn't you use xrange since you don't need the list, in python 2?

                                                            – UnitasBrooks
                                                            May 24 '18 at 15:32
















                                                          5














                                                          Reverse a string in python without using reversed() or [::-1]



                                                          def reverse(test):
                                                          n = len(test)
                                                          x=""
                                                          for i in range(n-1,-1,-1):
                                                          x += test[i]
                                                          return x





                                                          share|improve this answer



















                                                          • 1





                                                            Shouldn't you use xrange since you don't need the list, in python 2?

                                                            – UnitasBrooks
                                                            May 24 '18 at 15:32














                                                          5












                                                          5








                                                          5







                                                          Reverse a string in python without using reversed() or [::-1]



                                                          def reverse(test):
                                                          n = len(test)
                                                          x=""
                                                          for i in range(n-1,-1,-1):
                                                          x += test[i]
                                                          return x





                                                          share|improve this answer













                                                          Reverse a string in python without using reversed() or [::-1]



                                                          def reverse(test):
                                                          n = len(test)
                                                          x=""
                                                          for i in range(n-1,-1,-1):
                                                          x += test[i]
                                                          return x






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Dec 10 '14 at 12:57









                                                          akshaynagpalakshaynagpal

                                                          1,1481923




                                                          1,1481923








                                                          • 1





                                                            Shouldn't you use xrange since you don't need the list, in python 2?

                                                            – UnitasBrooks
                                                            May 24 '18 at 15:32














                                                          • 1





                                                            Shouldn't you use xrange since you don't need the list, in python 2?

                                                            – UnitasBrooks
                                                            May 24 '18 at 15:32








                                                          1




                                                          1





                                                          Shouldn't you use xrange since you don't need the list, in python 2?

                                                          – UnitasBrooks
                                                          May 24 '18 at 15:32





                                                          Shouldn't you use xrange since you don't need the list, in python 2?

                                                          – UnitasBrooks
                                                          May 24 '18 at 15:32











                                                          3














                                                          def reverse(input):
                                                          return reduce(lambda x,y : y+x, input)





                                                          share|improve this answer





















                                                          • 2





                                                            I clicked upvote, because I like this lambda expression. Unfortunately, it's the least efficient solution from all listed above (test: Gist palindrome.py )

                                                            – oski86
                                                            Jul 24 '15 at 16:32
















                                                          3














                                                          def reverse(input):
                                                          return reduce(lambda x,y : y+x, input)





                                                          share|improve this answer





















                                                          • 2





                                                            I clicked upvote, because I like this lambda expression. Unfortunately, it's the least efficient solution from all listed above (test: Gist palindrome.py )

                                                            – oski86
                                                            Jul 24 '15 at 16:32














                                                          3












                                                          3








                                                          3







                                                          def reverse(input):
                                                          return reduce(lambda x,y : y+x, input)





                                                          share|improve this answer















                                                          def reverse(input):
                                                          return reduce(lambda x,y : y+x, input)






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Jun 26 '15 at 4:56









                                                          josliber

                                                          37.4k1164101




                                                          37.4k1164101










                                                          answered Jun 26 '15 at 4:25









                                                          JavierJavier

                                                          473313




                                                          473313








                                                          • 2





                                                            I clicked upvote, because I like this lambda expression. Unfortunately, it's the least efficient solution from all listed above (test: Gist palindrome.py )

                                                            – oski86
                                                            Jul 24 '15 at 16:32














                                                          • 2





                                                            I clicked upvote, because I like this lambda expression. Unfortunately, it's the least efficient solution from all listed above (test: Gist palindrome.py )

                                                            – oski86
                                                            Jul 24 '15 at 16:32








                                                          2




                                                          2





                                                          I clicked upvote, because I like this lambda expression. Unfortunately, it's the least efficient solution from all listed above (test: Gist palindrome.py )

                                                          – oski86
                                                          Jul 24 '15 at 16:32





                                                          I clicked upvote, because I like this lambda expression. Unfortunately, it's the least efficient solution from all listed above (test: Gist palindrome.py )

                                                          – oski86
                                                          Jul 24 '15 at 16:32











                                                          3














                                                          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 = byterarray('Reverse this!', 'UTF-8')
                                                          b.reverse()
                                                          b.decode('UTF-8')`


                                                          will produce:



                                                          '!siht esreveR'





                                                          share|improve this answer






























                                                            3














                                                            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 = byterarray('Reverse this!', 'UTF-8')
                                                            b.reverse()
                                                            b.decode('UTF-8')`


                                                            will produce:



                                                            '!siht esreveR'





                                                            share|improve this answer




























                                                              3












                                                              3








                                                              3







                                                              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 = byterarray('Reverse this!', 'UTF-8')
                                                              b.reverse()
                                                              b.decode('UTF-8')`


                                                              will produce:



                                                              '!siht esreveR'





                                                              share|improve this answer















                                                              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 = byterarray('Reverse this!', 'UTF-8')
                                                              b.reverse()
                                                              b.decode('UTF-8')`


                                                              will produce:



                                                              '!siht esreveR'






                                                              share|improve this answer














                                                              share|improve this answer



                                                              share|improve this answer








                                                              edited Sep 25 '18 at 13:57

























                                                              answered Sep 25 '18 at 11:46









                                                              mdnmdn

                                                              33339




                                                              33339























                                                                  1














                                                                  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!")





                                                                  share|improve this answer




























                                                                    1














                                                                    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!")





                                                                    share|improve this answer


























                                                                      1












                                                                      1








                                                                      1







                                                                      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!")





                                                                      share|improve this answer













                                                                      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!")






                                                                      share|improve this answer












                                                                      share|improve this answer



                                                                      share|improve this answer










                                                                      answered May 4 '15 at 17:02









                                                                      buzhidaobuzhidao

                                                                      776626




                                                                      776626























                                                                          1














                                                                          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.






                                                                          share|improve this answer






























                                                                            1














                                                                            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.






                                                                            share|improve this answer




























                                                                              1












                                                                              1








                                                                              1







                                                                              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.






                                                                              share|improve this answer















                                                                              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.







                                                                              share|improve this answer














                                                                              share|improve this answer



                                                                              share|improve this answer








                                                                              edited Apr 16 '18 at 20:46

























                                                                              answered Apr 16 '18 at 20:38









                                                                              Nitin KhannaNitin Khanna

                                                                              503312




                                                                              503312























                                                                                  1














                                                                                  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





                                                                                  share|improve this answer




























                                                                                    1














                                                                                    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





                                                                                    share|improve this answer


























                                                                                      1












                                                                                      1








                                                                                      1







                                                                                      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





                                                                                      share|improve this answer













                                                                                      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






                                                                                      share|improve this answer












                                                                                      share|improve this answer



                                                                                      share|improve this answer










                                                                                      answered Oct 28 '18 at 11:51









                                                                                      AlexAlex

                                                                                      214




                                                                                      214























                                                                                          1














                                                                                          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.






                                                                                          share|improve this answer




























                                                                                            1














                                                                                            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.






                                                                                            share|improve this answer


























                                                                                              1












                                                                                              1








                                                                                              1







                                                                                              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.






                                                                                              share|improve this answer













                                                                                              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.







                                                                                              share|improve this answer












                                                                                              share|improve this answer



                                                                                              share|improve this answer










                                                                                              answered Dec 10 '18 at 18:23









                                                                                              Supa Mega Ducky Momo da WaffleSupa Mega Ducky Momo da Waffle

                                                                                              1




                                                                                              1























                                                                                                  1














                                                                                                  original = "string"

                                                                                                  rev_index = original[::-1]
                                                                                                  rev_func = list(reversed(list(original))) #nsfw

                                                                                                  print(original)
                                                                                                  print(rev_index)
                                                                                                  print(''.join(rev_func))





                                                                                                  share|improve this answer
























                                                                                                  • While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context.

                                                                                                    – Robert Columbia
                                                                                                    Dec 29 '18 at 11:11
















                                                                                                  1














                                                                                                  original = "string"

                                                                                                  rev_index = original[::-1]
                                                                                                  rev_func = list(reversed(list(original))) #nsfw

                                                                                                  print(original)
                                                                                                  print(rev_index)
                                                                                                  print(''.join(rev_func))





                                                                                                  share|improve this answer
























                                                                                                  • While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context.

                                                                                                    – Robert Columbia
                                                                                                    Dec 29 '18 at 11:11














                                                                                                  1












                                                                                                  1








                                                                                                  1







                                                                                                  original = "string"

                                                                                                  rev_index = original[::-1]
                                                                                                  rev_func = list(reversed(list(original))) #nsfw

                                                                                                  print(original)
                                                                                                  print(rev_index)
                                                                                                  print(''.join(rev_func))





                                                                                                  share|improve this answer













                                                                                                  original = "string"

                                                                                                  rev_index = original[::-1]
                                                                                                  rev_func = list(reversed(list(original))) #nsfw

                                                                                                  print(original)
                                                                                                  print(rev_index)
                                                                                                  print(''.join(rev_func))






                                                                                                  share|improve this answer












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered Dec 29 '18 at 0:42









                                                                                                  JEXJEX

                                                                                                  414




                                                                                                  414













                                                                                                  • While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context.

                                                                                                    – Robert Columbia
                                                                                                    Dec 29 '18 at 11:11



















                                                                                                  • While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context.

                                                                                                    – Robert Columbia
                                                                                                    Dec 29 '18 at 11:11

















                                                                                                  While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context.

                                                                                                  – Robert Columbia
                                                                                                  Dec 29 '18 at 11:11





                                                                                                  While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context.

                                                                                                  – Robert Columbia
                                                                                                  Dec 29 '18 at 11:11











                                                                                                  0














                                                                                                  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.






                                                                                                  share|improve this answer




























                                                                                                    0














                                                                                                    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.






                                                                                                    share|improve this answer


























                                                                                                      0












                                                                                                      0








                                                                                                      0







                                                                                                      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.






                                                                                                      share|improve this answer













                                                                                                      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.







                                                                                                      share|improve this answer












                                                                                                      share|improve this answer



                                                                                                      share|improve this answer










                                                                                                      answered Dec 29 '15 at 13:23









                                                                                                      Claudiu CreangaClaudiu Creanga

                                                                                                      3,80683275




                                                                                                      3,80683275























                                                                                                          0














                                                                                                          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





                                                                                                          share|improve this answer




























                                                                                                            0














                                                                                                            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





                                                                                                            share|improve this answer


























                                                                                                              0












                                                                                                              0








                                                                                                              0







                                                                                                              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





                                                                                                              share|improve this answer













                                                                                                              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






                                                                                                              share|improve this answer












                                                                                                              share|improve this answer



                                                                                                              share|improve this answer










                                                                                                              answered Jan 13 '18 at 14:21









                                                                                                              mattmatt

                                                                                                              405316




                                                                                                              405316























                                                                                                                  0














                                                                                                                  Do not know about the efficiency but a short solution found on the MIT lectures is



                                                                                                                  s = "abcd"

                                                                                                                  s[-1:-(len(s)+1):-1]
                                                                                                                  Out[5]: 'dcba'


                                                                                                                  You may read more about Slices to get a better understanding of this code.






                                                                                                                  share|improve this answer


























                                                                                                                  • Why would you include the start & stop, if the goal is to just reverse the string?

                                                                                                                    – Adam Parkin
                                                                                                                    Feb 21 at 16:34











                                                                                                                  • @Adam This one I got from MIT lectures. Not created by me.

                                                                                                                    – Krishnadas PC
                                                                                                                    Feb 21 at 17:15
















                                                                                                                  0














                                                                                                                  Do not know about the efficiency but a short solution found on the MIT lectures is



                                                                                                                  s = "abcd"

                                                                                                                  s[-1:-(len(s)+1):-1]
                                                                                                                  Out[5]: 'dcba'


                                                                                                                  You may read more about Slices to get a better understanding of this code.






                                                                                                                  share|improve this answer


























                                                                                                                  • Why would you include the start & stop, if the goal is to just reverse the string?

                                                                                                                    – Adam Parkin
                                                                                                                    Feb 21 at 16:34











                                                                                                                  • @Adam This one I got from MIT lectures. Not created by me.

                                                                                                                    – Krishnadas PC
                                                                                                                    Feb 21 at 17:15














                                                                                                                  0












                                                                                                                  0








                                                                                                                  0







                                                                                                                  Do not know about the efficiency but a short solution found on the MIT lectures is



                                                                                                                  s = "abcd"

                                                                                                                  s[-1:-(len(s)+1):-1]
                                                                                                                  Out[5]: 'dcba'


                                                                                                                  You may read more about Slices to get a better understanding of this code.






                                                                                                                  share|improve this answer















                                                                                                                  Do not know about the efficiency but a short solution found on the MIT lectures is



                                                                                                                  s = "abcd"

                                                                                                                  s[-1:-(len(s)+1):-1]
                                                                                                                  Out[5]: 'dcba'


                                                                                                                  You may read more about Slices to get a better understanding of this code.







                                                                                                                  share|improve this answer














                                                                                                                  share|improve this answer



                                                                                                                  share|improve this answer








                                                                                                                  edited Feb 18 at 7:27

























                                                                                                                  answered Feb 18 at 7:22









                                                                                                                  Krishnadas PCKrishnadas PC

                                                                                                                  1,9571719




                                                                                                                  1,9571719













                                                                                                                  • Why would you include the start & stop, if the goal is to just reverse the string?

                                                                                                                    – Adam Parkin
                                                                                                                    Feb 21 at 16:34











                                                                                                                  • @Adam This one I got from MIT lectures. Not created by me.

                                                                                                                    – Krishnadas PC
                                                                                                                    Feb 21 at 17:15



















                                                                                                                  • Why would you include the start & stop, if the goal is to just reverse the string?

                                                                                                                    – Adam Parkin
                                                                                                                    Feb 21 at 16:34











                                                                                                                  • @Adam This one I got from MIT lectures. Not created by me.

                                                                                                                    – Krishnadas PC
                                                                                                                    Feb 21 at 17:15

















                                                                                                                  Why would you include the start & stop, if the goal is to just reverse the string?

                                                                                                                  – Adam Parkin
                                                                                                                  Feb 21 at 16:34





                                                                                                                  Why would you include the start & stop, if the goal is to just reverse the string?

                                                                                                                  – Adam Parkin
                                                                                                                  Feb 21 at 16:34













                                                                                                                  @Adam This one I got from MIT lectures. Not created by me.

                                                                                                                  – Krishnadas PC
                                                                                                                  Feb 21 at 17:15





                                                                                                                  @Adam This one I got from MIT lectures. Not created by me.

                                                                                                                  – Krishnadas PC
                                                                                                                  Feb 21 at 17:15











                                                                                                                  -1














                                                                                                                  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






                                                                                                                  share|improve this answer




























                                                                                                                    -1














                                                                                                                    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






                                                                                                                    share|improve this answer


























                                                                                                                      -1












                                                                                                                      -1








                                                                                                                      -1







                                                                                                                      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






                                                                                                                      share|improve this answer













                                                                                                                      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







                                                                                                                      share|improve this answer












                                                                                                                      share|improve this answer



                                                                                                                      share|improve this answer










                                                                                                                      answered Mar 8 '17 at 12:10









                                                                                                                      Chowdeswara RaoChowdeswara Rao

                                                                                                                      93




                                                                                                                      93























                                                                                                                          -1














                                                                                                                          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





                                                                                                                          share|improve this answer
























                                                                                                                          • While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.

                                                                                                                            – hellow
                                                                                                                            Nov 11 '18 at 7:21
















                                                                                                                          -1














                                                                                                                          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





                                                                                                                          share|improve this answer
























                                                                                                                          • While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.

                                                                                                                            – hellow
                                                                                                                            Nov 11 '18 at 7:21














                                                                                                                          -1












                                                                                                                          -1








                                                                                                                          -1







                                                                                                                          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





                                                                                                                          share|improve this answer













                                                                                                                          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






                                                                                                                          share|improve this answer












                                                                                                                          share|improve this answer



                                                                                                                          share|improve this answer










                                                                                                                          answered Sep 2 '18 at 10:03









                                                                                                                          Kiran SkKiran Sk

                                                                                                                          403321




                                                                                                                          403321













                                                                                                                          • While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.

                                                                                                                            – hellow
                                                                                                                            Nov 11 '18 at 7:21



















                                                                                                                          • While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.

                                                                                                                            – hellow
                                                                                                                            Nov 11 '18 at 7:21

















                                                                                                                          While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.

                                                                                                                          – hellow
                                                                                                                          Nov 11 '18 at 7:21





                                                                                                                          While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.

                                                                                                                          – hellow
                                                                                                                          Nov 11 '18 at 7:21











                                                                                                                          -2














                                                                                                                          s = 'Hello world'



                                                                                                                          s[::-1]



                                                                                                                          in the above example label s or variable s is holding string which contain Hello world string and on second step i m printing reverse of Hello world string by taking starting from everything to everything in reverse step order with -1.






                                                                                                                          share|improve this answer




























                                                                                                                            -2














                                                                                                                            s = 'Hello world'



                                                                                                                            s[::-1]



                                                                                                                            in the above example label s or variable s is holding string which contain Hello world string and on second step i m printing reverse of Hello world string by taking starting from everything to everything in reverse step order with -1.






                                                                                                                            share|improve this answer


























                                                                                                                              -2












                                                                                                                              -2








                                                                                                                              -2







                                                                                                                              s = 'Hello world'



                                                                                                                              s[::-1]



                                                                                                                              in the above example label s or variable s is holding string which contain Hello world string and on second step i m printing reverse of Hello world string by taking starting from everything to everything in reverse step order with -1.






                                                                                                                              share|improve this answer













                                                                                                                              s = 'Hello world'



                                                                                                                              s[::-1]



                                                                                                                              in the above example label s or variable s is holding string which contain Hello world string and on second step i m printing reverse of Hello world string by taking starting from everything to everything in reverse step order with -1.







                                                                                                                              share|improve this answer












                                                                                                                              share|improve this answer



                                                                                                                              share|improve this answer










                                                                                                                              answered Jan 13 '18 at 14:58









                                                                                                                              user128364user128364

                                                                                                                              1,1301110




                                                                                                                              1,1301110























                                                                                                                                  -4














                                                                                                                                  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)





                                                                                                                                  share|improve this answer



















                                                                                                                                  • 1





                                                                                                                                    It is not a nice solution to have such a long code for such a trivial task.

                                                                                                                                    – Hunter_71
                                                                                                                                    Oct 9 '17 at 23:14
















                                                                                                                                  -4














                                                                                                                                  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)





                                                                                                                                  share|improve this answer



















                                                                                                                                  • 1





                                                                                                                                    It is not a nice solution to have such a long code for such a trivial task.

                                                                                                                                    – Hunter_71
                                                                                                                                    Oct 9 '17 at 23:14














                                                                                                                                  -4












                                                                                                                                  -4








                                                                                                                                  -4







                                                                                                                                  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)





                                                                                                                                  share|improve this answer













                                                                                                                                  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)






                                                                                                                                  share|improve this answer












                                                                                                                                  share|improve this answer



                                                                                                                                  share|improve this answer










                                                                                                                                  answered Feb 3 '16 at 10:40









                                                                                                                                  olgaolga

                                                                                                                                  446




                                                                                                                                  446








                                                                                                                                  • 1





                                                                                                                                    It is not a nice solution to have such a long code for such a trivial task.

                                                                                                                                    – Hunter_71
                                                                                                                                    Oct 9 '17 at 23:14














                                                                                                                                  • 1





                                                                                                                                    It is not a nice solution to have such a long code for such a trivial task.

                                                                                                                                    – Hunter_71
                                                                                                                                    Oct 9 '17 at 23:14








                                                                                                                                  1




                                                                                                                                  1





                                                                                                                                  It is not a nice solution to have such a long code for such a trivial task.

                                                                                                                                  – Hunter_71
                                                                                                                                  Oct 9 '17 at 23:14





                                                                                                                                  It is not a nice solution to have such a long code for such a trivial task.

                                                                                                                                  – Hunter_71
                                                                                                                                  Oct 9 '17 at 23:14











                                                                                                                                  -4














                                                                                                                                  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





                                                                                                                                  share|improve this answer





















                                                                                                                                  • 1





                                                                                                                                    what is the point of using a while loop here?

                                                                                                                                    – AsheKetchum
                                                                                                                                    Mar 29 '17 at 15:18
















                                                                                                                                  -4














                                                                                                                                  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





                                                                                                                                  share|improve this answer





















                                                                                                                                  • 1





                                                                                                                                    what is the point of using a while loop here?

                                                                                                                                    – AsheKetchum
                                                                                                                                    Mar 29 '17 at 15:18














                                                                                                                                  -4












                                                                                                                                  -4








                                                                                                                                  -4







                                                                                                                                  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





                                                                                                                                  share|improve this answer















                                                                                                                                  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






                                                                                                                                  share|improve this answer














                                                                                                                                  share|improve this answer



                                                                                                                                  share|improve this answer








                                                                                                                                  edited Sep 22 '16 at 11:03









                                                                                                                                  Kalpesh Dusane

                                                                                                                                  1,05421425




                                                                                                                                  1,05421425










                                                                                                                                  answered Mar 24 '16 at 18:28









                                                                                                                                  sudistacksudistack

                                                                                                                                  9714




                                                                                                                                  9714








                                                                                                                                  • 1





                                                                                                                                    what is the point of using a while loop here?

                                                                                                                                    – AsheKetchum
                                                                                                                                    Mar 29 '17 at 15:18














                                                                                                                                  • 1





                                                                                                                                    what is the point of using a while loop here?

                                                                                                                                    – AsheKetchum
                                                                                                                                    Mar 29 '17 at 15:18








                                                                                                                                  1




                                                                                                                                  1





                                                                                                                                  what is the point of using a while loop here?

                                                                                                                                  – AsheKetchum
                                                                                                                                  Mar 29 '17 at 15:18





                                                                                                                                  what is the point of using a while loop here?

                                                                                                                                  – AsheKetchum
                                                                                                                                  Mar 29 '17 at 15:18











                                                                                                                                  -5














                                                                                                                                  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)]





                                                                                                                                  share|improve this answer



















                                                                                                                                  • 1





                                                                                                                                    What was eliminated? This continues to work just fine in Py3...

                                                                                                                                    – ShadowRanger
                                                                                                                                    Nov 4 '16 at 5:54











                                                                                                                                  • The question asks for the reverse of a string, and you instead give a list??

                                                                                                                                    – user21820
                                                                                                                                    Feb 25 '17 at 13:47











                                                                                                                                  • you need a .join or something to make it a valid answer

                                                                                                                                    – AsheKetchum
                                                                                                                                    Mar 29 '17 at 15:17











                                                                                                                                  • BTW, [c for c in string] is tantamount to list(string).

                                                                                                                                    – Right leg
                                                                                                                                    Sep 8 '17 at 12:02
















                                                                                                                                  -5














                                                                                                                                  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)]





                                                                                                                                  share|improve this answer



















                                                                                                                                  • 1





                                                                                                                                    What was eliminated? This continues to work just fine in Py3...

                                                                                                                                    – ShadowRanger
                                                                                                                                    Nov 4 '16 at 5:54











                                                                                                                                  • The question asks for the reverse of a string, and you instead give a list??

                                                                                                                                    – user21820
                                                                                                                                    Feb 25 '17 at 13:47











                                                                                                                                  • you need a .join or something to make it a valid answer

                                                                                                                                    – AsheKetchum
                                                                                                                                    Mar 29 '17 at 15:17











                                                                                                                                  • BTW, [c for c in string] is tantamount to list(string).

                                                                                                                                    – Right leg
                                                                                                                                    Sep 8 '17 at 12:02














                                                                                                                                  -5












                                                                                                                                  -5








                                                                                                                                  -5







                                                                                                                                  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)]





                                                                                                                                  share|improve this answer













                                                                                                                                  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)]






                                                                                                                                  share|improve this answer












                                                                                                                                  share|improve this answer



                                                                                                                                  share|improve this answer










                                                                                                                                  answered Jul 19 '16 at 17:32









                                                                                                                                  alejandro izquierdoalejandro izquierdo

                                                                                                                                  244




                                                                                                                                  244








                                                                                                                                  • 1





                                                                                                                                    What was eliminated? This continues to work just fine in Py3...

                                                                                                                                    – ShadowRanger
                                                                                                                                    Nov 4 '16 at 5:54











                                                                                                                                  • The question asks for the reverse of a string, and you instead give a list??

                                                                                                                                    – user21820
                                                                                                                                    Feb 25 '17 at 13:47











                                                                                                                                  • you need a .join or something to make it a valid answer

                                                                                                                                    – AsheKetchum
                                                                                                                                    Mar 29 '17 at 15:17











                                                                                                                                  • BTW, [c for c in string] is tantamount to list(string).

                                                                                                                                    – Right leg
                                                                                                                                    Sep 8 '17 at 12:02














                                                                                                                                  • 1





                                                                                                                                    What was eliminated? This continues to work just fine in Py3...

                                                                                                                                    – ShadowRanger
                                                                                                                                    Nov 4 '16 at 5:54











                                                                                                                                  • The question asks for the reverse of a string, and you instead give a list??

                                                                                                                                    – user21820
                                                                                                                                    Feb 25 '17 at 13:47











                                                                                                                                  • you need a .join or something to make it a valid answer

                                                                                                                                    – AsheKetchum
                                                                                                                                    Mar 29 '17 at 15:17











                                                                                                                                  • BTW, [c for c in string] is tantamount to list(string).

                                                                                                                                    – Right leg
                                                                                                                                    Sep 8 '17 at 12:02








                                                                                                                                  1




                                                                                                                                  1





                                                                                                                                  What was eliminated? This continues to work just fine in Py3...

                                                                                                                                  – ShadowRanger
                                                                                                                                  Nov 4 '16 at 5:54





                                                                                                                                  What was eliminated? This continues to work just fine in Py3...

                                                                                                                                  – ShadowRanger
                                                                                                                                  Nov 4 '16 at 5:54













                                                                                                                                  The question asks for the reverse of a string, and you instead give a list??

                                                                                                                                  – user21820
                                                                                                                                  Feb 25 '17 at 13:47





                                                                                                                                  The question asks for the reverse of a string, and you instead give a list??

                                                                                                                                  – user21820
                                                                                                                                  Feb 25 '17 at 13:47













                                                                                                                                  you need a .join or something to make it a valid answer

                                                                                                                                  – AsheKetchum
                                                                                                                                  Mar 29 '17 at 15:17





                                                                                                                                  you need a .join or something to make it a valid answer

                                                                                                                                  – AsheKetchum
                                                                                                                                  Mar 29 '17 at 15:17













                                                                                                                                  BTW, [c for c in string] is tantamount to list(string).

                                                                                                                                  – Right leg
                                                                                                                                  Sep 8 '17 at 12:02





                                                                                                                                  BTW, [c for c in string] is tantamount to list(string).

                                                                                                                                  – Right leg
                                                                                                                                  Sep 8 '17 at 12:02





                                                                                                                                  protected by Jon Clements Apr 11 '13 at 8:29



                                                                                                                                  Thank you for your interest in this question.
                                                                                                                                  Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                                                                  Would you like to answer one of these unanswered questions instead?



                                                                                                                                  Popular posts from this blog

                                                                                                                                  How to send String Array data to Server using php in android

                                                                                                                                  Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

                                                                                                                                  Is anime1.com a legal site for watching anime?