To reverse a string in Python the bellow are the best ways so far:
Write [::-1] to do slicing in Python starting at first character, until last, step by 1 in reverse (-1). It’s a pretty nice way to impress your imaginary friends.
Option 1
s = s[::-1] # (start, stop, step)
Option 2
s = ''.join(reversed(s))
Whole code demo
# How to reverse a string in Python 3
s = "hello world"
#The fastest way - go thru all chars in reverse order one by one: -1
rev1 = s[::-1] # (start, stop, step)
rev2 = ''.join(reversed(s)) # build a string
print(s)
print(rev1)
print(rev2)
#Output:
#hello world
#dlrow olleh
#dlrow olleh
Write a comment or no, it’s up to you.
Leave a Reply