• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / How to reverse a string in Python

How to reverse a string in Python

Author: Aditya Raj
Last Updated: July 22, 2021

We can perform many operations on strings in python. These operations include splitting a string, string concatenation, reversing a string, slicing a string and many more. In this article, we will reverse a string in python using different ways.

Reverse string using slicing

The first and easiest way to reverse a string in python is to use slicing. We can create a slice of any string by using the syntax string_name[ start : end : interval ] where start and end are start and end index of the sub string which has to be sliced  from the string. The interval parameter is used to select characters at specified intervals.

To reverse an entire string using slicing, we will leave start and end parameters as empty. This will cause the slice to be created from the entire string. The interval parameter will be specified as -1 so that consecutive characters are included in the sliced string in reverse order. This can be  understood from the following example.

myString = "PythonForBeginners"
reversedString = myString[:: -1]
print("Original String is:", myString)
print("Reversed String is:", reversedString)

Output:

Original String is: PythonForBeginners
Reversed String is: srennigeBroFnohtyP

Reverse string using for loop

To reverse a string using a for loop, we will first calculate the length of the string. Then, we will create a new empty string. Afterwards, We will access the string character by character from the end till start and will add it to the newly created string. This will result in the creation of a new string which has characters in reverse order compared to the original string. This can be easily understood from the following example.

myString = "PythonForBeginners"
reversedString = ""
strlen = len(myString)
for count in range(strlen):
    character = myString[strlen - 1 - count]
    reversedString = reversedString + character

print("Original String is:",myString)
print("Reversed String is:", reversedString)

Output:

Original String is: PythonForBeginners
Reversed String is: srennigeBroFnohtyP

Reverse string using a Python list

We can also use a list to reverse a string in python. In this method, First, we will convert the string into a list of characters and will create a new empty string. Afterwards, we will take out characters one by one from the end of the list and then we will perform string concatenation to add the characters to the new string. 

In this way, a new string will be created which will be a reverse of the original string. This can be done as follows.

myString = "PythonForBeginners"
charList=[]
charList[:0] = myString
reversedString = ""

strlen = len(charList)
for count in range(strlen):
    character = charList.pop()
    reversedString = reversedString+character

print("Original String is:", myString)
print("Reversed String is:", reversedString)

Output:

Original String is: PythonForBeginners
Reversed String is: srennigeBroFnohtyP

Reverse string using recursion

To use recursion to reverse a string, we will use the following procedure.

Suppose we define a function reverseString(input_string) to reverse the string. First we will check if the input_string is empty, If yes then we will return the input_string. Otherwise we will  take the last character out from the input_string and will call reverseString() function for the remaining part and will concatenate its output after the last character of the input_string as follows.

myString = "PythonForBeginners"


def reverseString(input_string):
    strlen = len(input_string)
    if strlen == 0:
        return ""
    else:
        last = input_string[-1]
        rest = input_string[0:strlen - 1]
        return last + reverseString(rest)


reversedString = reverseString(myString)
print("Original String is:", myString)
print("Reversed String is:", reversedString)

Output:

Original String is: PythonForBeginners
Reversed String is: srennigeBroFnohtyP

Using reversed() method

The reversed() method returns a reverse iterator of any iterable object passed to it as input argument. We can use the reverse iterator to create the reverse of the input string. We will first create an empty string and then we will add the characters in reverse order by iterating the reverse iterator returned by reversed() function as follows.

myString = "PythonForBeginners"
reverse_iterator = reversed(myString)
reversedString = ""
for char in reverse_iterator:
    reversedString = reversedString + char

print("Original String is:", myString)
print("Reversed String is:", reversedString)

Output:

Original String is: PythonForBeginners
Reversed String is: srennigeBroFnohtyP

Conclusion

In this article, we have studied different methods to reverse a string in python. .We can also write the programs used in this article with exception handling using python try except to make the programs more robust and handle errors in a systematic way . Stay tuned for more informative articles.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary โ€“ How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 ยท PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us