- 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
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.
- txt="today climate is very cool"[::-1]
- txt1="hello world"[::-1]
- print(txt)
- print(txt1)
No comments