search

How to reverse a string in Python?

To reverse a string in Python, you can use string slicing or the reversed() function. Here are examples of both approaches:

Using string slicing:

my_string = "Hello, World!"
reversed_string = my_string[::-1]
print(reversed_string)
# Output: "!dlroW ,olleH"

In this example, the [::-1] slicing syntax is used to create a reversed copy of the string my_string. The [::-1] indicates that the slice should start from the end of the string and move towards the beginning with a step of -1, effectively reversing the string.

Using the reversed() function:

my_string = "Hello, World!"
reversed_string = ''.join(reversed(my_string))
print(reversed_string)
# Output: "!dlroW ,olleH"

In this example, the reversed() function is used to return a reverse iterator for the characters of the string my_string. The join() function is then used to join the reversed characters back into a single string.

Both approaches will give you the same result: a reversed version of the original string.

Note that both approaches create a new string object that is the reversed version of the original string. If you need to perform operations on individual characters of the string in a reversed order, you can use a loop or iterate over the reversed string directly without creating a new string object.

Related Questions You Might Be Interested