How to reverse string python
How to reverse string python
Reverse string in Python (6 different ways)
Python string library doesn’t support the in-built “reverse()” as done by other python containers like list, hence knowing other methods to reverse string can prove to be useful. This article discusses several ways to achieve it in Python.
Example:
Method 1: Reverse a string in Python using a loop
In this example, we call a function to reverse a string, which iterates to every element and intelligently joins each character in the beginning so as to obtain the reversed string.
Time complexity: O(n)
Auxiliary Space: O(1)
Implementation:
Python3
Method 2: Reverse a string in Python using recursion
The string is passed as an argument to a recursive function to reverse the string. In the function, the base condition is that if the length of the string is equal to 0, the string is returned. If not equal to 0, the reverse function is recursively called to slice the part of the string except the first character and concatenate the first character to the end of the sliced string. ‘
Time complexity: O(n)
Auxiliary Space: O(n)
How to Reverse String in Python
Introduction
Although it may not be a common thing to do in any real-world scenario, reversing strings is a pretty common operation you’ll face in a job interview. Especially if you are applying for a job in a programming language that doesn’t have built-in methods for reversing strings. By asking you to reverse a string, an interviewer can get a pretty accurate impression of how you approach analyzing the problem and building a solution from scratch.
Also, since there can be plenty of solutions for this problem, this is your chance to shine and show your awareness of the different execution speeds between different algorithms, thus create the best possible solution.
In this article, we’ll take a look at how to reverse a string in Python. We’ll consider several possible solutions and compare them, so you can choose the one that best fits your needs.
Strings in Python
Note: The actual object used to deal with strings in Python is called the str object. It essentially represents a string data type.
Reversing a String in Python
Recommended Solution: Using the Slice Notation
Note: If you’d like to learn more about slicing strings in Python, you should read the article «Python: Slice Notation on Strings»
We’ve used the slicing operator on our example_str in the previously described way, which will yield us the reversed version of our original string:
Advice: Wrapping each section of a code in a function is generally a good practice! Besides improving the code readability it actually helps you create more modular and reusable code. Therefore, you can wrap each of the following code snippets in the function in the same manner as shown in this section.
Using join() and reversed()
First of all, reversed() returns a reversed iterator for the string passed as its argument. That enables us to go over the original string backward and append its characters to the empty string using str.join() function:
This will create a reversed copy of the original string:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Using a for Loop
Note: Notice how we’ve been adding each character to the reversed string, but strings in Python are immutable. We can do that because Python, essentially, creates a modified copy of a string each time we append a character to it, before solidifying the result as an immutable string and returning it.
An alternative approach is to iterate over the original string forwards, from the start to the end, and create the reversed version of the original string in the loop itself:
This will give us the same result as using the reversed iterator in the loop.
Using a while Loop
Another loop we can use to reverse a string is the while loop. This approach is a bit more complicated than others, but can give you a great insight in how reversing string works on a lower level:
Which will result in:
Conclusion
How do I reverse words in a string with Python
I am trying to reverse words of a string, but having difficulty, any assistance will be appreciated:
What I get now is: eman ym si tahw
However, I am trying to get: tahw is ym eman (individual words reversed)
12 Answers 12
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Since everyone else’s covered the case where the punctuation moves, I’ll cover the one where you don’t want the punctuation to move.
Breaking this down.
re is python’s regex module, and re.sub is the function in that module that handles substitutions. It has three required parameters.
The second is either a string to substitute in, or a function that takes in a re.MatchObject and outputs a string. I’m using a lambda (or nameless) function that simply outputs the matched string, reversed.
The third is the string you want to do a find in a replace in.
The built-in reversed outputs a reversed object, which you have to cast back to string, so I generally prefer the [::-1] option.
How to Reverse a String in Python
Learn how to reverse a String in Python.
There is no built-in function to reverse a String in Python.
Example
Reverse the string «Hello World»:
Example Explained
We have a string, «Hello World», which we want to reverse:
The String to Reverse
Create a slice that starts at the end of the string, and moves backwards.
Slice the String
Now we have a string txt that reads «Hello World» backwards.
Print the String to demonstrate the result
Print the List
Create a Function
If you like to have a function where you can send your strings, and return them backwards, you can create a function and insert the code from the example above.
Example
def my_function(x):
return x[::-1]
mytxt = my_function(«I wonder how this text looks like backwards»)
Example Explained
Create a function that takes a String as an argument.
Create a Function
def my_function(x):
return x[::-1]
mytxt = my_function(«I wonder how this text looks like backwards»)
Slice the string starting at the end of the string and move backwards.
Slice the String
def my_function(x):
return x [::-1]
mytxt = my_function(«I wonder how this text looks like backwards»)
Return the backward String
Return the String
def my_function(x):
return x[::-1]
mytxt = my_function(«I wonder how this text looks like backwards»)
Call the function, with a string as a parameter:
Call the Function
def my_function(x):
return x[::-1]
mytxt = my_function(«I wonder how this text looks like backwards»)
Print the result:
Print the Result
def my_function(x):
return x[::-1]
mytxt = my_function(«I wonder how this text looks like backwards»)
We just launched
W3Schools videos
COLOR PICKER
Get certified
by completing
a course today!
CODE GAME
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Web Courses
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Python String doesn’t have a built-in reverse() function. However, there are various ways to reverse a string in Python.
1. How to Reverse a String in Python?
Some of the common ways to reverse a string are:
1.1) Python Reverse String using Slicing
If you run above Python script, the output will be:
1.2) Reverse String using For Loop
Output: Reverse String using for loop = FE∂çBA
1.3) Reverse a String using While Loop
1.4) Reverse a String using join() and reversed()
1.5) Python Reverse String using List reverse()
1.6) Python Reverse String using Recursion
2. Best Way to Reverse a String in Python
The below table presents the results and slowness of an algorithm from the best one.
Algorithm | TimeIt Execution Time (Best of 5) | Slowness |
---|---|---|
Slicing | 0.449 usec | 1x |
List reverse() | 2.46 usec | 5.48x |
reversed() + join() | 2.49 usec | 5.55x |
for loop | 5.5 usec | 12.25x |
while loop | 9.4 usec | 20.94x |
Recursion | 24.3 usec | 54.12x |
3. Summary
We should use slicing to reverse a string in Python. Its code is very simple and small and we don’t need to write our own logic to reverse the string. Also, it’s the fastest way to reverse a string as identified by the above test executions.
You can checkout complete python script and more Python examples from our GitHub Repository.
4. References
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.