How to reverse string in Python ?

Author: neptune | 16th-May-2022
🏷️ #Python

Different ways to reverse String in Python.

String is a widely used datatype in Python just like a list. In most of the interviews, a question was asked How to reverse a string in Python?
In this article, we will see a different way to reverse a String in Python.

1. Using Extended Slice Syntax:

Extended slice method takes three parameters [ start index: end index: increment ] just like the for a loop.

Example:

testString = 'Neptuneworld'

testString=testString[::-1]

print(testString)

Output:


2.Using BuildIn method Reversed():

Reversed method returns a string reversed object which we can see that’s why we use to join and convert that object to a string using join.

Example :

testString = 'Neptuneworld'

testString=””.join(reversed(testString))

print(testString)

Output :


3. Using for loop:

In this method, we iterate the string and add the element to the start of initialized empty string.

Example:

testString = 'Neptuneworld'

revString = str()

for ch in testString:

revString = ch + revString

print(revString)

Output:

4.Using Recursive Function:

def reverse(testString):

if len(testString) == 0:

return testString

else:

return reverse(testString[1:]) + testString[0]

print(reverse("NeptuneWorld"))


5.Using List  :

Using list also we can reverse the string as shown below.

testString = 'Neptuneworld'

revString = []

for i in range(len(testString)-1,-1,-1):

revString.append(testString[i])


print(''.join(revString))


Thanks for Reading !!!





πŸ‘‰ Read More
How to extract Speech from Video using Python?
How to download video from youtube using python module ?
Deploy Django project on AWS with Apache2 and mod_wsgi module.
Best Python package manager and package for virtual environment ?
Mostly asked Python Interview Questions - 2023.
Core Python Syllabus for Interviews
Python Built-in functions lambda, map, filter, reduce.
Python 3.9 new amazing features ?
10 Proven Ways to Earn Money Through Python
Building a Simple Chatbot with Python and openpyxl
5 Languages that Replace Python with Proof
Monkey Patching in Python: A Powerful Yet Controversial Technique
Best Practices for Managing Requests Library Sessions When Interacting with Multiple APIs ?
How to Ensure Proper Namespace Handling in XML with Python's lxml Library
How to Update XML Files in Python?
Explore more Blogs...