C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: With a list of characters, returned by the list comprehension, we can manipulate the ordering of the characters.
Reverse: We invoke the list's reverse() method on the characters list. This changes the order of the letters in-place.
Join: We join the characters together on an empty delimiter. This concatenates the chars into a new, reversed string.
Python program that implements string reverse method
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)
Output
cat
tac
abcde
edcba
So: The trick to manipulating strings is to convert them to lists first. We then just manipulate the list elements.