There is no built in function in Python for reversing a string, but that doesn’t mean it can’t be done. To reverse a string in Python, a little bit of extended slice syntax needs to be used, so you’re going to have to add something to your code that looks like this: [::-1].
Here’s what we mean:
p = backwards print p[::-1]
- Python Programming – String Slices
- Python Programming – List Functions And Methods
- How to Use Python to Multiply Strings | Multiply Strings in Python with Examples
The result of the above code should be as follows:
This works because within the extended slice syntax, you tell the function where to begin and end (by inserting two semicolons you’re telling the function to begin at the beginning and end at the end), and then to iterate through the string backwards (by using -1…using -2 would still print backwards but skip over every other letter, so the result would be: srwcb).
Try it out for yourself to see how easy it can be to reverse or iterate backwards through a string in Python!