The Best Approach for Reversing Strings in Python

Python String does not include an in-built reverse() function. Nevertheless, there are multiple approaches available to reverse a string in Python.

How can a string be reversed in Python?

There are several commonly used methods for reversing a string.

  • Using Slicing to create a reverse copy of the string.
  • Using for loop and appending characters in reverse order
  • Using while loop to iterate string characters in reverse order and append them
  • Using string join() function with reversed() iterator
  • Creating a list from the string and then calling its reverse() function
  • Using Recursion

1.2) Utilize Slicing in Python to Reverse a String.

def reverse_slicing(s):
    return s[::-1]

input_str = 'ABç∂EF'

if __name__ == "__main__":
    print('Reverse String using slicing =', reverse_slicing(input_str))

Running the Python script above will result in the following output.

Reverse String using slicing = FE∂çBA

Reversing a string using a for loop.

def reverse_for_loop(s):
    s1 = ''
    for c in s:
        s1 = c + s1  # appending chars in reverse order
    return s1

input_str = 'ABç∂EF'

if __name__ == "__main__":
    print('Reverse String using for loop =', reverse_for_loop(input_str))

The result obtained by using a for loop to reverse the string is = FE∂çBA.

Reverse a string by utilizing a while loop.

def reverse_while_loop(s):
    s1 = ''
    length = len(s) - 1
    while length >= 0:
        s1 = s1 + s[length]
        length = length - 1
    return s1

input_str = 'ABç∂EF'

if __name__ == "__main__":
    print('Reverse String using while loop =', reverse_while_loop(input_str))

To reverse a string, you can utilize the join() function and reversed() function.

def reverse_join_reversed_iter(s):
    s1 = ''.join(reversed(s))
    return s1

Using the `reverse()` function in Python, reverse the order of characters in a string.

def reverse_list(s):
    temp_list = list(s)
    temp_list.reverse()
    return ''.join(temp_list)

1.6) How to reverse a string in Python using recursion.

def reverse_recursion(s):
    if len(s) == 0:
        return s
    else:
        return reverse_recursion(s[1:]) + s[0]

2. The Top Method to Reverse a String in Python

There are various algorithms available for reversing a string, and we have explored six of them so far. However, when it comes to selecting the most suitable algorithm for reversing a string, we can employ the timeit module. By running multiple iterations of these functions and calculating the average time taken, we can determine the optimal choice. All of the aforementioned functions are stored in a python script called string_reverse.py. To obtain accurate measurements, I executed each function individually for 100,000 iterations using the timeit module, and then calculated the average time from the fastest five runs.

$ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_slicing("ABç∂EF"*10)'
100000 loops, best of 5: 0.449 usec per loop

$ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_list("ABç∂EF"*10)'
100000 loops, best of 5: 2.46 usec per loop

$ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_join_reversed_iter("ABç∂EF"*10)'
100000 loops, best of 5: 2.49 usec per loop

$ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_for_loop("ABç∂EF"*10)'
100000 loops, best of 5: 5.5 usec per loop

$ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_while_loop("ABç∂EF"*10)'
100000 loops, best of 5: 9.4 usec per loop

$ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_recursion("ABç∂EF"*10)'
100000 loops, best of 5: 24.3 usec per loop
Python Reverse String
Algorithm TimeIt Execution Time (Best of 5) Slowness
Slicing 0.449 usec 1x
List reverse() 2.46 usec 5.48x
reversed() + join() 2.49 usec 5.55x
for loop 5.5 usec 12.25x
while loop 9.4 usec 20.94x
Recursion 24.3 usec 54.12x

Provide a single alternative paraphrase for the statement:

3. Summary:

Using slicing is the most efficient method to reverse a string in Python. This approach requires writing a minimal and straightforward code, without the need for implementing a custom logic. Based on the previous test runs, it has been identified as the fastest way to reverse a string.

From our GitHub Repository, you have the option to access the full python script and additional Python examples.

4. Citations

  • reversed() API Doc
  • str.join() API Doc

 

More tutorials

Adding a string to a Python variable(Opens in a new browser tab)

Server Configurations Frequently Used for Your Web Application(Opens in a new browser tab)

jshell for interactive Java programming(Opens in a new browser tab)

arrow operator in the C programming language!(Opens in a new browser tab)

Tutorial on Java Server Faces (JSF)(Opens in a new browser tab)

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds