How to Reverse a String in Python
If you are wondering how to reverse a string in Python, this can easily be done with slice notation. However, I will show you a few quick ways to reverse Python strings. I will list these in order difficulty.
Two Main Points
- Strings are Immutable. So, we can’t change them just create a copy.
- Strings are sliceable.
- There is no built-in string reverse function
Reverse Python Strings with Slice Notation
When slicing a string, you should think about the structure of the actual slice. The slice will be preformed in the following method, [start:stop:step]. So we can instruct the slice direction by using the step portion of the slice.
string = "open the door"
#now let's reverse this string
string[::-1]
Output:
'rood eht nepo'
As you see that you can easily use the negative step to reverse a python string. Now you don’t need save the string as a variable you can directly use the slice on the string.
'open the door'[::-1]
Output
'rood eht nepo'
Using the Reversed Function with a Join
Yes, there is an actual reversed function that we can utilize for to reverse a python list. However, this is a slower an slightly more complicated method. We will also need to to use the join function for this to work. So we are essentially breaking our string to a list and then reversing it.
The structure will look like this.
''.join(reversed(string))
So we can use thee same structure to give a reversed python string
' '.join(reversed('open the door'))
Output
'rood eht nepo'
output:
Or just using the saved string in the variable.
' '.join(reversed(string))
Output
'rood eht nepo'