W3docs

How do I reverse a string in Python?

To reverse a string in Python, you can use the following method:

To reverse a string in Python, you can use the following method:

Define a function to reverse a string in Python

def reverse_string(string):
    return string[::-1]

You can then use the function like this:

Reverse a string in Python

def reverse_string(string):
    return string[::-1]

reverse_string("hello")

This will return the reversed string "olleh".

You can also reverse a string by using the built-in reversed() function. Here's an example of how to do that:

Define a function to reverse a string in Python by the reversed function

def reverse_string(string):
    return "".join(reversed(string))

You can then use the function like this:

Reverse a string in Python by the reversed function

def reverse_string(string):
    return "".join(reversed(string))

reverse_string("hello")

This will also return the reversed string "olleh".