Skip to main content

5 Ways to Reverse String in Python

Hello everyone, in this tutorial we’ll see different ways to reverse string in Python.

As we know, we can reverse a list using reverse() method but Python doesn’t have the reverse() method for string.

Here are some alternate and easy ways to reverse a string.

Ways to Reverse String in Python

1. Using Loop

string1 =  "the crazy programmer"
string2 = ""

i = len(string1)-1

while(i>=0):
  string2 = string2 + string1[i]
  i = i-1

print "original = " + string1
print "reverse  = " + string2

Output:

original = the crazy programmer
reverse = remmargorp yzarc eht

In above program, we’ve started a loop from the last index (length-1) to first index (0) of string1. In each step of loop, it will pick the character from right-side in string1 and concatenate with string2.

2. Using Recursion

def reverse_it(string):
  if len(string)==0:
    return string
  else:
    return reverse_it(string[1:]) + string[0]
    print "added " + string[0]

string1 = "the crazy programmer"
string2 = reverse_it(string1)

print "original = " + string1
print "reversed = " + string2

In above program, there is a reverse_it() method which accepts a string and then it will check if the string is empty or not, if empty then it will return the string otherwise it will call itself by passing string from its second character to last character.

String = “hello”

Print string[1:]

Output:  ‘ello’

After calling reverse_it() method again and again there will be a point when string will be empty then the condition

if len(string) == 0:

will be true , it will return the string.  return statement will throw the execution, where it came from.

So in

Return reverse_it(string[1:])  +  string[0]

the “+ string[0] “ will be executed next, which will add the first letter at last.

3. Using Stack

def create_stack():
  #it will  create a List named as stack and return it
  stack = []
  return stack

def push(stack,element):
  #it will add a new element to List
  stack.append(element)

def pop(stack):
  #it will delete the last element from  List
  if len(stack) == 0:
    return
  return stack.pop()

def reverse(string):

  #method to reverse the string using stack's functions
  n = len(string)
  
  #to create a empty list (stack)
  stack = create_stack()

  #inserting character of string into List
  for i in range(0,n):
    push(stack,string[i])

  #making string empty
  string = ""

  #getting last element of the List (stack) and storing it into string
  for i in range(0,n):
    string = string + pop(stack)
  return string

string1 = "the crazy programer"
string2 = reverse(string1)

print "original = " + string1
print "reversed = " + string2

In above program, we’re using concept of stack having push and pop functions.

To implement stack concept we’re using list.

When we call reverse() method, it will create a list named as ‘stack’ and insert all the characters of string into list using push() method. At last it will fetch all the elements in the list from last to first one by one and store them into the string.

4. Using Extended Slice

string = "the crazy programmer"
print "original = " + string

string = string[::-1]
print "reversed = " + string

Mostly extended slice is used for skipping the steps but if we put -1 in third ‘step’ or ‘stride’ argument then we can get the reverse of a string, list and tupple.

5. Using List

string = "the crazy programmer"
print "original = " + string

#convrting string into list
list1 = list(string)

#applying reverse method of list
list1.reverse()

#converting list into string
string = ''.join(list1)
print "reversed = " + string

String doesn’t have reverse() method but lists have. So we are converting string into list, performing reverse() operation and again converting it back into string using ‘ ’.join() method.

Comment below if you have queries or know any other way to reverse a string in python.

The post 5 Ways to Reverse String in Python appeared first on The Crazy Programmer.



from The Crazy Programmer https://www.thecrazyprogrammer.com/2017/12/reverse-string-python.html

Comments

Popular posts from this blog

dotnet sdk list and dotnet sdk latest

Can someone make .NET Core better with a simple global command? Fanie Reynders did and he did it in a simple and elegant way. I'm envious, in fact, because I spec'ed this exact thing out in a meeting a few months ago but I could have just done it like he did and I would have used fewer keystrokes! Last year when .NET Core was just getting started, there was a "DNVM" helper command that you could use to simplify dealing with multiple versions of the .NET SDK on one machine. Later, rather than 'switching global SDK versions,' switching was simplified to be handled on a folder by folder basis. That meant that if you had a project in a folder with no global.json that pinned the SDK version, your project would use the latest installed version. If you liked, you could create a global.json file and pin your project's folder to a specific version. Great, but I would constantly have to google to remember the format for the global.json file, and I'd constan

R vs Python for Machine Learning

There are so many things to learn before to choose which language is good for Machine Learning. We will discuss each and everything about R as well as Python and the situation or problem in which situation we have to use which language. Let’s start Python and R are the two most Commonly used Programming Languages for Machine Learning and because of the popularity of both the languages Novice or you can say fresher are getting confused, whether they should choose R or Python language to commence their career in the Machine learning domain. Don’t worry guys through this article we will discuss R vs Python for Machine Learning. So, without exaggerating this article let’s get started. We will start it from the very Basics things or definitions. R vs Python for Machine Learning Introduction R is a programming language made by statisticians and data miners for statistical analysis and graphics supported by R foundation for statistical computing. R also provides high-quality graphics and

Top Tips For PCB Design Layout

Are you thinking about designing a printed circuit board? PCBs are quite complicated, and you need to make sure that the layout that you choose is going to operate as well as you want it to. For this reason, we have put together some top tips for PCB design layout. Keep reading if you would like to find out more about this. Leave Enough Space One of the most important design tips for PCB layout is that you need to make sure that you are leaving enough space between the components. While many people might think that packing components closely is the best route to take, this can cause problems further down the line. This is why we suggest leaving extra space for the wires that will spread. This way, you’ll have the perfect PCB design layout. Print Out Your Layout Struggling to find out if your components sizes match? Our next tip is to print out your layout and compare the printed version to your actual components. Datasheets can sometimes come with errors, so it doesn’t hurt to do