Linux, OpenSource, Programming And Hacks

Feb 22, 2018

3 Common ways to Reverse a String in Python

Feb 22, 2018
One of the very common problems in any programming language is how to reverse a String.

Let's see a few ways to do this in python.

1. Using String Slicing

well first of all the most easy way.. Here we are using the power of String Slicing. Just a single line command!

-1 at the last index means reading from end. and the first two empty index means that we are considering the whole string. 

mystring = "Hello World"
rev = mystring[::-1]

 2. Using join method and reversed method

reversed function returns a reverse iterator over the values of sequence and join basically joins those with the given separator, which is '' (an empty string) in this case.

mystring = "Hello World"

rev = ''.join(reversed(mystring))



3. Using String concatenation and for loop

mystring = "Hello World"

rev = ""

for i in mystring):
    rev = i + rev


No comments:

Post a Comment