How to reverse a string in python
Python does not have a native reverse method on the
str class. To reverse a string, either
- Use list slicing
- Use the
reversed(string)function on the string and using
"".join()to return a string.
Let's look into each in more detail.
This is simply achieved by using the step option
[::-1] in string slicing
string = "python is the most elegant" reversed_string = string[::-1] print(reversed_string) # output: tnagele tsom eht si nohtyp
This is probably the best way since it computes in linear time. According to this StackOverflow answer, the time complexity is linear and is equal to the length of the slice.
Using the reversed() method
This method is more verobase. You convert the reversed object
<reversed object at 0x7fc8b5cb1310> to a string using
string = "python is the most elegant" reversed_string = "".join(reversed(string)) print(reversed_string) # output: tnagele tsom eht si nohtyp
This method has an m*n time complexity and takes two steps to implement. It's best to stick with method 1.
There you have it, two ways to reverse a string in python. Please join my newsletter to be notified of new posts. Happy Pythoning! Adios ✌🏾🧡.