HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How do I reverse a string in Python?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
stringhowpythonreverse

Problem

There is no built in reverse method for Python's str object. How can I reverse a string?

Solution

Using slicing:

>>> 'hello world'[::-1]
'dlrow olleh'


Slice notation takes the form [start:stop:step]. In this case, we omit the start and stop positions since we want the whole string. We also use step = -1, which means, "repeatedly step from right to left by 1 character".

Code Snippets

>>> 'hello world'[::-1]
'dlrow olleh'

Context

Stack Overflow Q#931092, score: 3161

Revisions (0)

No revisions yet.