Reverse string in python

 Reverse string in Python by most common methods

Many types of methods are already provided in the string class within Python technology and one of them is the slicing method. String slicing allows us to perform a variety of operations with any string inside Python. It is very easy to reverse a string using the slicing method.

Reverse a string by string slicing method in Python

s1 = "Hello SanjayTechTalk"
#string reverse by slicing method
print("Revers String in Python by slicing Method")
print(s1[::- 1])

output

Revers String in Python by slicing Method 
klaThceTyajnaS olleH

Reverse String by Indexing method in Python

But if you want to reverse the string in Python by the indexing method then you can use this code


s1 = "Hello SanjayTechTalk"
print("Revers String in Python by for Loop Method")
s1_lenth = len(s1)
s1_revers = ""
for n in range(s1_lenth-1, -1, -1):
s1_revers = s1_revers+s1[n]
print(s1_revers)

output

Revers String in Python by For Loop Method 
klaThceTyajnaS olleH

Revers String by while loop method in Python

If you want to reverse a string in Python by using while loop method you can use this code

s1 = "Hello SanjayTechTalk"
print("Revers String in Python by While Loop Method")
s1_lenth = len(s1)
s2_lenth = s1_lenth
s2_revers = ""
while s2_lenth > 0:
s2_revers = s2_revers+s1[s2_lenth-1]
s2_lenth = s2_lenth-1
print(s2_revers)

output

Revers String in Python by While Loop Method 
klaThceTyajnaS olleH

Leave a Comment