Reverse
string
Programs sometimes have unusual requirements. For example we might need to reverse the characters in a string
. This could help for generating a unique key from some data.
With list comprehension, we get the characters of a string
. And then we can reverse those characters with reverse()
and call join()
to join them back again.
Here we introduce a reverse_string
method. This method receives a string
and returns a reversed form of it. We first use list comprehension to get a character list.
reverse()
method on the characters list. This changes the order of the letters in-place.string
.def reverse_string(value): # Get characters from the string. characters = [c for c in value] # Reverse list of characters. characters.reverse() # Join characters back into string with empty delimiter. return "".join(characters) # Test our string reversal method. test1 = "cat" reversed1 = reverse_string(test1) print(test1) print(reversed1) test2 = "abcde" reversed2 = reverse_string(test2) print(test2) print(reversed2)cat tac abcde edcba
Lists are powerful in Python. We can reverse them. With a list comprehension, meanwhile, we can quickly construct a list of characters from an expression.
By reversing strings, we learn how to manipulate strings in many ways. We can change the individual characters, or reorder the characters in any fashion. This is powerful.