89DEVs

Python: How to reverse a string?

How to reverse a string in Python?

Use slice notation with backwards step [::-1] or the reversed() function together with the join() method. The built-in reverse() method of Python lists can not be used for strings, however we can turn the string into a list and use it.

option 1: slice notation with backwards step

Use the slice notation not for slicing the string, just for stepping backward one by one: [::-1] # reverse a string using slice notation myString = 'Anna' myReversedString = myString[::-1] print(myReversedString) annA

option 2: reversed() function

The reversed() function reverses an object. Use join() to create the reversed string. myString = 'Anna' myReversedString = ''.join(reversed(myString)) print(myReversedString) annA The join() method is necessary because the reversed() function returns a reversed object and not a string.

option 3: list.reverse() method

To use the list.reverse() method, convert the string into a list. Then reverse the list and finally join the list again. # reverse string using list.reverse() myString = 'Anna' myList = list(myString) myList.reverse() myResult = ''.join(myList) print(myResult) The string is converted into a string, reversed then joined and printed. annA

option 4: define our own reverse() function

Python doesn't offer a built-in reverse() method for strings, only for lists. Define your own function using slice notation. def reverse(input_string): return input_string[::-1] print(reverse('Anna')) It's simple and it works, the reversed string is returned. annA

                
        

Summary


Click to jump to section