How to reverse a string in Python 3

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

#hello world
#dlrow olleh
#dlrow olleh

Write a comment or no, it’s up to you.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.