• The reverse string in python is not an in-built function.
  • By creating the slice operation we can perform the reverse function.
  • In this slice operation, we create the slice that starts with the end of the string and moves backward.
  • String reverse in python example program
Example: " abcdefg"[::-1]

                     gfedcba

 right to left indexing:              [-7]    [-6]    [-5]    [-4]      [-3]     [-2]      [-1]

                                                    a          b      c        d          e          f         g 

left to right indexing:             [0]         [1]     [2]     [3]     [4]       [5]        [6]

  • In the above example, we are having the string  "abcdefg " which we want to reverse. so create a slice that starts with the end of the string and moves backward.
  • here it starts with the end index that is indicated with -1 and moves backward as 5,4,3,2,1,0.
  • -1 index  is g
  • 5 index is f
  • 4 index is e
  • 3 index is d
  • 2 index is c
  • 1 index is b
  • 0 index is a
  • so the final output is gfedcba.

#write a python code to demonstrate string reverse.

  1. txt="today climate is very cool"[::-1]
  2. txt1="hello world"[::-1]
  3. print(txt)
  4. print(txt1)
Output:    looc yrev si etamilc yadot
                  dlrow olleh


Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu