Skip to content
← Back to Community
How to reverse a string
Profile icon
ArmedWithStew

How do you reverse a string in python? Is it reversed(string) or something?

Voters
Profile icon
zainabamirah
Profile icon
KurtusHsu1
Profile icon
8W1414
Profile icon
ArmedWithStew
Comments
hotnewtop
Profile icon
[deleted]

This is the simplest way:

message = 'hello, python' reversed_message = message[::-1] print(reversed_message) # 'nohtyp ,olleh'
Profile icon
ash15khng

@malvoliothegood To add on, if you want to know why this works, it is because of how string slicing works.
"string"[start:stop:step]
In this case start is where in the string to start, stop is where to stop, and step is how many characters to skip. Example: "123456"[::2] is equal to "135"
So when you do [::-1] you get every character of the string but stepped backwards. (hope this makes sense)

Profile icon
[deleted]

@ash15khng
Good explanation!

Profile icon
ash15khng