The simplest way is to use Python double colon slicing with a negative step value:
my_string = "abc123"
reversed_string = my_string[::-1]
print(reversed_string)
"321cba"
PythonYou can also use the builtin reversed
method, which will “Return a reverse iterator over the values of the given sequence” according to its official help()
. Note that this returns an iterator, not a string, so you’ll have to do a bit more work to create the reversed string:
my_string = "abc123"
reverse_iterator = reversed(my_string)
# <reversed at 0x1051bead0>
new_string = ""
for char in reverse_iterator:
new_string += char
print(new_string)
"321cba"
PythonYou could also build a list from the reversed object and then .join
it like so:
my_string = "abc123"
reverse_iterator = reversed(my_string)
# <reversed at 0x1051bead0>
"".join(list(reversed_iterator))
# "321cba"
PythonBoth of these methods work equally well on lists.