Python Tutorial (33) - Example: String Reversal

Time: Column:Python views:207

Reversing a String in Python

This section will cover how to reverse a given string and output the result in reverse order.

Example 1: Using String Slicing

str = 'Runoob'
# Reversing the string using slicing
print(str[::-1])

Output:

boonuR

In this example, we use Python's slicing feature to reverse the string by specifying a step of -1, which moves through the string from the end to the beginning.

Example 2: Using reversed() Function

str = 'Runoob'
# Reversing the string using reversed() and join()
print(''.join(reversed(str)))

Output:

boonuR

In this second example, we use the reversed() function to reverse the string, and then the join() function to convert the reversed iterable back into a string.

Both methods yield the same result.