HOW TO REVERSE A STRING IN PYTHON?

0 0
Read Time:7 Minute, 10 Second

Introduction to Python:

It is high-level, interpreted and general purpose programming language. Just like HTML, CSS & JAVASCRIPT python can be used for various types of programming, software development along with web development. Python is multipurpose. For instance, it can be used for various things like back end web, mobile app development, desktop app, software development. It is also used for processing big data and to perform mathematical computations. By using python framework, we can also write system scripts. Python was designed to be highly extensible. Developers get the flexibility in choosing their coding methodology as python strives for simpler, less-cluttered syntax and grammar. It has been observed that scripting languages such as python are more productive than the conventional languages like C and JAVA since there are programming problems in C and JAVA like string manipulation & more memory consumption.

Today, in this blog we will see what python string is & how python strings can be reversed by using various methods.

What is Python String?

  • The collection of the Unicode character is called as Python String.
  • Though, Python has various functions for string manipulation however, Python string library doesn’t support the in-built “reverse()” function.
  • There is no need to worry since there are number of ways to reverse the string.
  • The below mentioned methods are the ones through which Python strings can be reversed.
  • By using for loop
  • BY using while loop
  • By using the slice operator
  • By using the reversed() function
  • By using the recursion

Before starting with the reverse string have a look at top Python developer skills, Visit here.

Let’s take a look in detail.

·         By using for loop:

In this method, we will reverse the given string using for loop.

  1. def reverse_string(str):  
  2.  str1 = “”   # Declaring empty string to store the reversed string  
  3.  for i in str:  
  4.   str1 = i + str1  
  5.   return str1    # It will return the reverse string to the caller function  
  6.  str = “JavaTpoint”    # Given String       
  7. print(“The original string is: “,str)  
  8. print(“The reverse string is”,reverse_string(str)) # Function call  

Result:

('The original string is: ', 'JavaTpoint')
('The reverse string is', 'tniopTavaJ')

Interpretation-

In the above code, we have declared the reverse_string() function and passed the str argument. In the function body, we have declared empty string variable str1 that will hold the reversed string. Next, for the loop iterated every element of the given string, join each character in the beginning and store in the str1 variable. After the complete iteration, it returned the reverse order string str1 to the caller function. It printed the result to the screen.

·     By using while loop:

Python string can also be reversed by using a while loop. Let’s try to understand it by seeing the below mentioned example.

Instance –

  1. # Reverse string  
  2. # Using a while loop  
  3. str = “JavaTpoint” #  string variable  
  4. print (“The original string  is : “,str)   
  5. reverse_String = “”  # Empty String  
  6. count = len(str) # Find length of a string and save in count variable  
  7. while count > 0:   
  8. reverse_String += str[ count – 1 ] # save the value of str[count-1] in reverseString  
  9. count = count – 1 # decrement index  
  10. print (“The reversed string using a while loop is : “,reverse_String)# reversed string  

Result:

('The original string  is : ', 'JavaTpoint')
('The reversed string using a while loop is : ', 'tniopTavaJ')

Interpretation:

In the above code, we have declared a str variable that holds string value. We initialized a while loop with a value of the string. In each iteration, the value of str[count-1] concatenated to the reverse_String and decremented the count value. A while completed its iteration and returned the reverse order string.

 

·     Using the slice operator:

Python string can also be reversed by using extended slice operator. Let’s try to understand it by seeing the below mentioned example.

Instance –

  1. #  Reverse a string    
  2. # using  slice syntax   
  3. # reverse(str) Function to reverse a string   
  4. def reverse(str):   
  5.  str = str[::-1]   
  6.  return str  
  7. s = “JavaTpoint”  
  8. print (“The original string  is : “,s)   
  9. print (“The reversed string using extended slice operator  is : “,reverse(s))  

Result:

('The original string  is : ', 'JavaTpoint')
('The reversed string(using extended slice syntax) is : ', 'tniopTavaJ')

Interpretation:

Generally, a slice operator accepts three parameters – start, stop and step. We provided the no value to start and end index, which indicates the start index is 0 and the end is n-1 by default. The step size is -1; it means the string continues the traverse from the end and goes to the 1 index position.

·     By using reverse function with join:

Python provides the reversed() function to reverse the string. Let’s try to understand it by seeing the below mentioned example.

Instance –

  1. #reverse a string using reversed()   
  2. # Function to reverse a string   
  3. def reverse(str):   
  4. string = “”.join(reversed(str)) # reversed() function inside the join() function  
  5.  return string   
  6. s = “JavaTpoint” 
  7. print (“The original string is : “,s)   
  8. print (“The reversed string using reversed() is : “,reverse(s) )  

Result:

('The original string is : ', 'JavaTpoint')
('The reversed string using reversed() is : ', 'tniopTavaJ')

Interpretation:

In the function body, we declared the empty string separated by .dot operator. The reversed() string returned the reverse string it joined with the empty string separated using the join() function.

 

·     By using recursion():

The string can also be reversed using the recursion. It is a process where function calls itself. See the below mentioned example.

Instance –

  1. # reverse a string    
  2. # using recursion   
  3. def reverse(str):   
  4. if len(str) == 0: # Checking the lenght of string  
  5. return str   
  6. else:   
  7. return reverse(str[1:]) + str[0]   
  8. str = “Devansh Sharma”   
  9. print (“The original string  is : “, str)     
  10. print (“The reversed string(using recursion) is : “, reverse(str))  

Result:

('The original string is : ', 'JavaTpoint')
('The reversed string(using reversed) is : ', 'tniopTavaJ')

Interpretation:

In the above code, we have defined a function that accepts the string as an argument. In the function body, we defined the base condition of recursion, if a length of a string is 0, then the string is returned, and if not then we called the function recursively. The slice operator slice the string expects the first character and concatenated to the end of the slice string.

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %
Previous post 10 Amazing Benefits to Use Swipe Machine Online
Online Salwar Kameez Next post Indian Ethnic Wedding collections perfect wedding outfit for Bride – Kolkozy Fashion

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published.