Thursday, July 22, 2021

Python for Beginners: How to reverse a string in Python

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.

The post How to reverse a string in Python appeared first on PythonForBeginners.com.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...