in python how to reverse a string

Published on Aug. 22, 2023, 12:15 p.m.

To reverse a string in Python, you can use slicing to create a reverse copy of the string. Here’s an example:

original_str = "hello world"
reversed_str = original_str[::-1]
print(reversed_str)

In this example, [::-1] creates a slice that starts from the end of the string and goes to the beginning of the string, with a step of -1, effectively reversing the order of characters in the string.

Another approach is to use a loop to iterate over the characters in the string and append them to a new string in reverse order. Here’s an example:

original_str = "hello world"
reversed_str = ""
for i in range(len(original_str) - 1, -1, -1):
    reversed_str += original_str[i]
print(reversed_str)

In this example, the loop starts from the end of the string and iterates backwards, appending each character to reversed_str.

Both of these approaches will output dlrow olleh for the original_str variable. I hope this helps! Let me know if you have any further questions.

Tags:

related content