Python
string manipulation
reverse string
programming tutorial
Python tips

How do I reverse a string in Python?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

To reverse a string in Python, there are several methods available, each with unique advantages. This article will delve into these methods, offering technical explanations and examples. Additionally, a table summarizing key points will help reinforce understanding.

String Reversal Methods

1. Using Slicing

String slicing is a concise and Pythonic way of reversing a string. It uses the syntax string[start:end:step]. To reverse a string, you can omit the start and end, and use a step of -1.

python
1# Example using string slicing
2original_string = "Hello, World!"
3reversed_string = original_string[::-1]
4print(reversed_string)  # Output: !dlroW ,olleH

Technical Explanation: Slicing with a step of -1 starts at the end of the string, stepping backwards to the beginning.

2. Using the reversed() Function

The reversed() function can be applied to obtain an iterator that iterates over the string in reverse. This iterator can then be passed to the join() method to form a reversed string.

python
1# Example using reversed() function
2original_string = "Hello, World!"
3reversed_string = ''.join(reversed(original_string))
4print(reversed_string)  # Output: !dlroW ,olleH

Technical Explanation: reversed() does not return a string but an iterator over the elements of the input in reverse order.

3. Using a Loop

Alternatively, a loop can be used to build the reversed string by iterating over the original string from last to first character.

python
1# Example using a loop
2original_string = "Hello, World!"
3reversed_string = ''
4for char in original_string:
5    reversed_string = char + reversed_string
6print(reversed_string)  # Output: !dlroW ,olleH

Technical Explanation: In each iteration, the current character is prepended to the accumulating result, which reverses the order of characters.

4. Using ''.join() and List Comprehensions

A list comprehension can be used to iterate over a string in reverse and then apply ''.join() on the result.

python
1# Example using list comprehension
2original_string = "Hello, World!"
3reversed_string = ''.join([original_string[i] for i in range(len(original_string) - 1, -1, -1)])
4print(reversed_string)  # Output: !dlroW ,olleH

Technical Explanation: The range function generates indices in reverse order, and the list comprehension constructs a list of characters in reverse sequence.

Summary Table

Below is a table summarizing the methods to reverse a string, their simplicity, and performance considerations:

MethodDescriptionPerformanceNotes
SlicingUtilizes Python's slicing syntax to directly reverse the string.O(n) - EfficientMost Pythonic and concise.
reversed() + join()Uses the reversed() function and joins the iterator to form a string.O(n) - EfficientReadable but not as concise.
LoopManually iterates through the string to build it in reverse order.O(n) - Less efficientMore control but verbose.
List ComprehensionCombines a list comprehension with range to achieve reversal, followed by joining the list.O(n) - Less efficientLess concise than slicing.

Additional Details

Reversing Multiline Strings

The techniques listed above can also reverse multiline strings. However, note that each line is treated as continuous text. To reverse entire lines within a multiline string, you'd need to split the lines, reverse them individually, and then join them.

python
1# Example - Reverse each line in a multiline string
2multiline_string = "Hello,\nWorld!"
3lines = multiline_string.split('\n')
4reversed_lines = [''.join(reversed(line)) for line in lines]
5reversed_multiline_string = '\n'.join(reversed_lines)
6print(reversed_multiline_string)
7# Output:
8# olleH,
9# !dlroW

Memory Considerations

String slicing and the use of reversed() are memory-efficient since strings are immutably sliced. However, constructing a new string or list might lead to additional memory usage, especially for large strings.

Conclusion

Reversing a string in Python is a common operation with multiple solutions. Choosing between these methods often depends on readability preferences and specific use cases. In most situations, the slicing method is preferred for its balance of clarity and elegance. Understanding the nuances of each technique, their performance, and memory implications will enable you to make informed decisions when manipulating strings in Python.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.