Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

string reverse in python

  • 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.
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




This post first appeared on Java Tutorial - InstanceOfJava, please read the originial post: here

Share the post

string reverse in python

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×