reversing a string in Python

Under the Python programming language domain, a String is defined as character data presented in an ordered sequence. What is character data? When you are working on an office suite software or word processing app, the bottom of the screen or monitor you are using always keeps a record of the word count and characters. Anything that you type on the Keyboard and is displayed on the interface of this word software or even a source code editor qualifies as the definition of character data.

Uniqueness of Strings in Python

The immutable nature of Strings in Python makes them unchangeable once created. The unchangeable nature of these Unicode characters represented through arrays of bytes makes them an ideal substitute to cater for the absence of the Character data type in Python. Therefore, what you see as a single Character on a Python program code is interpreted as a String of length 1. Accessing defined String elements is through the use of square brackets.

Regarding String reversal or reversing a String under Python, the said statement is in black and white. It implies that you can take its interpretation at face value.

Python String Reverse Picture Demo
Python String Reverse Picture Demo

Methods for Reversing Strings through Python

Despite these high praises and unique attributes we give Python Strings, it does not offer a direct inbuilt methodology of implementing String reversal. We have to be creative and come up with our own customizable Python methods approach to achieving this article’s objective. Lucky enough, there are several interesting ways of exploiting String reversal under the Python program language, and we are going to explore each of them thoroughly.

Since the Python libraries don’t allocate us an in-built reverse (), we do not have to be jealous when List and other Python containers get this favor. We can achieve the same through the following approaches.

Reversing a Python String Using For Loop

# Python program to achieve String reversal through Loops
def reverse (my_string):
	str  =  ""
	for x in my_string:
		str = x + str
	return str
my_string = "CodeUnderScored"
print ("Original String before reversal is: ",end="")
print (my_string)
print ("The reversed String through Python's For Loop method is: ",end="")
print (reverse(my_string))

The following output is expected from running this code.

Original String before reversal is: CodeUnderScored
The reversed String through Python's For Loop method is: derocSrednUedoC   

The above code implements a reverse function to achieve String reversal. It iterates or loops through the defined string elements that need reversal by intelligently reverse-joining each of these String character elements. It appears like the String characters were typed backward to a human eye.

Reversing a Python String Using While Loop

Like the For Loop, the While Loop can also achieve Python’s String reversal effectively. The following code example offers a better understanding of this underlying concept.

# Python program code to String reversal through a While Loop implementation
# Define and implement the While Loop function you will use to reverse a Python String
def reverse (some_string):
	str1 = ''
	string_length = len(some_string) - 1
	while string_length >= 0:
		str1 = str1 + some_string[string_length]
		string_length = string_length - 1
	return str1
# Include a driver code to demonstrate the effectiveness of the above created code
my_string = "CodeUnderScored"
print ("Original String before reversal is: ",end="")
print (my_string)
print ("The reversed String through Python's While Loop method is: ",end="")
print (reverse(my_string))   

The expected output from running this code is:

Original String before reversal is: CodeUnderScored
The reversed String through Python's While Loop method is: derocSrednUedoC

The While Loop checks for the length of the String to make sure it is not empty, i.e., string_length >= 0. Afterward, the loop function takes a previously initialized empty string instance and assigns it the defined String character elements (CodeUnderScored), which are then reversed.

Reversing a Python String Using Recursion

Python works very well with a recursion function. The way recursive functions work is to call themselves or initialize their own function call. Both the fields of mathematics and programming value the use of recursions. Because this function calls itself, a Python program that executes through recursion will end or exit from the execution when the set condition does not exceed 0 or matches 0.

# Python program to demonstrate String reversal through recursion
def reverse (my_string):
	if len(my_string) == 0:
		return my_string
	else:
		return reverse (my_string[1:]) + my_string[0]
my_string = "CodeUnderScored"
print ("Original String before reversal is: ",end="")
print (my_string)
print ("The reversed String through Python's Recursion method is: ",end="")
print (reverse(my_string))     

The expected output is as follows:

Original String before reversal is: CodeUnderScored
The reversed String through Python's Recursion method is: derocSrednUedoC

In the defined code above, we passed our String as an argument to an existing recursive function to meet the String reversal objective. The breakdown of the recursive function algorithm is as follows. First, it creates a base condition that checks whether the string is empty or has some characters. It achieves this objective by checking whether the String length is 0. A 0 String length implies that it does not have any character elements, and its execution will return an empty string. If the String length is not 0, then there are some character elements in play, and the recursive function can execute. It recursively slices through the defined String character elements except for the first String character. Afterward, it concatenates the remaining string characters in a reverse order behind the first String character.

Reversing a Python String Using Stack

A stack is a data structure type in Python that caters to or supports push and pull operations. Such operations take place under an amortized O(1) time. Python’s built-in Lists implemented as dynamic arrays help create a decent Stack.

# Python program to achieve String reversal through Stack

# Start by defining a function that should create an empty Stack
# Also note that an initialized empty Stack has the size of 0
def create_Stack ():
	mystack = []
	return mystack
# Define a function that should determine the Stack size you created
def size (mystack):
	return len (mystack)
# If the size of the Stack turns out to be 0, then it is an empty Stack
def isEmpty (mystack):
	if size (mystack) == 0:
		return true
# Define a function that will add String element characters to a Stack
# The size of the Stack should increase by 1
def push (mystack, item):
	mystack.append(item)
# Define a function to remove added String element characters from a Stack. 
# The size of the Stack should decrease by 1
def pop (mystack):
	if isEmpty (mystack): return
	return mystack.pop()
# Finally, we can now define a Stack-based function to demonstrate String reversal. 
def reverse (some_string):
	x = len (some_string)
	# Define an empty Stack instance
	mystack = create_Stack ()
	# Push all the String character elements inside the defined empty Stack
	for z in range (0,x,1):
		push (mystack, some_string[z])
	# We should make the some_string instance empty 
	# Its a logical move since the String character elements will be saved under mystack
	some_string = ""
	# Finally, we should be able to pop all the acquired String character
	# elements and push them back to some_string
	for z in range (0,x,1):
		some_string+=pop (mystack)
	return some_string
# As usual, we cannot execute this code without the driver code
my_string = "CodeUnderScored"
print ("Original String before reversal is: ",end="")
print (my_string)
print ("The reversed String through Python's Stack method is: ",end="")
print (reverse(my_string))     

The expected output from running this code is as follows:

Original String before reversal is: CodeUnderScored
The reversed String through Python's Stack method is: derocSrednUedoC

We created an empty Stack instance, and afterward, each of the String character elements got pushed inside it. These string character elements inside the stack then get popped one by one and returned as reversed String character elements.

Reversing a Python String Using Extended Slice Syntax

There is no easy way to explain what extend slicing is under Python without sounding like a robot. Slice syntax is useful in referencing sequences’ sub-parts. These sequences are typical Lists and Strings. For example, a slicing syntax instance like z[a:b:f] will return every fth element from a to b. A z[a:b:-f] slicing syntax instance yields every fth character element of z in reverse order.

# Python program code that demonstrates String reversal through extended slice syntax
# Define the function that we will use to reverse our string
def reverse (some_string):
	some_string = some_string[::-1]
	return some_string
# Again we launch our driver code
my_string = "CodeUnderScored"
print ("Original String before reversal is: ",end="")
print (my_string)
print ("The reversed String through Python's Extended Slicing Syntax method is: ",end="")
print (reverse(my_string)) 	

The result of this Python code execution should be similar to the following:

Original String before reversal is: CodeUnderScored
The reversed String through Python's Extended Slicing Syntax method is: derocSrednUedoC

The extended slicing methodology implements a step field into the used String array such that we have a syntax skeleton that resembles [start, stop, step]. Looking closely at the example code above, we do not have the start and stop fields, but we do have the step field. The absence of the two fields defaults them to 0, which is also the value inherited by the String length at that instance. The step field has a value of -1, which tells the defined reverse () function to read a String value from its ending character element to its starting character element and therefore successfully reversing any String.

Reversing a Python String Using Reverse () and Join () Functions

# Python program code that demonstrates the use of reverse() and join() to 
# accomplish String reversal

# Define and implement both reverse() and join() functions
def reverse (some_string):
	some_string = "".join(reversed(some_string))
	return some_string
# Implement the needed driver code
my_string = "CodeUnderScored"
print ("Original String before reversal is: ",end="")
print (my_string)
print ("The reversed String through Python's Reverse () and Join () Method is: ",end="")
print (reverse(my_string)) 	 

The expected output from running this code is as follows:

Original String before reversal is: CodeUnderScored
The reversed String through Python's Reverse () and Join () Method is: derocSrednUedoC

The above defined and implemented reverse function performs an iteration of the availed String through a reversed or backward iteration approach. The String character elements in this iteration sequence are joined by the join() functions linked with an empty string instance that plays a major role in reverse-ordering the resultant reversed string formed.

Reversing a Python String Using List Reverse () Function

# Python program code to demonstrate String reversal through the List reverse () approach 
# Define and implement the List reverse function we will reference
def reverse_list (some_string):
	some_list = list (some_string)
	some_list.reverse()
	return ''.join(some_list)
# As usual, we now include the driver code
my_string = "CodeUnderScored"
print ("Original String before reversal is: ",end="")
print (my_string)
print ("The reversed String through Python's List Reverse Method is: ",end="")
print (reverse_list(my_string)) 

The expected output from executing this code is as follows:

Original String before reversal is: CodeUnderScored
The reversed String through Python's List Reverse Method is: derocSrednUedoC

Which of These Python’s String Reversal Approaches is the Best?

Multiple existing algorithms help us achieve effective Python’s String reversals. We have enjoyed working on implementing several Python String reversals through seven approaches in this article. However, an instance might pop up where you only need to use the best of the above-exposed String reverse Algorithmic approaches. Here, some exposure to Python’s Timeit Module will carry us through this hurdle. This module exposes the execution properties of defined Python functions.

In our case, we did a simulation to determine which function is the fastest in attaining String reversal except for the Stack approach since the length of its code validates the assumption that it would trail. Consider the following tabulated results after exposing our String Reverse functions through Python’s Timeit Module.

AlgorithmTimeIt Execution TimeSlowness
Extended Slicing ()0.449 microseconds1x
List Reverse ()2.46 microseconds5.48x
Reverse () + Join ()2.49 microseconds5.55x
For Loop ()5.5 microseconds12.25x
While Loop ()9.4 microseconds20.94x
Recursion ()24.3 microseconds54.12x
Tabulation of the different execution clocking times of Python Reverse String Algorithms

Final Note

When dealing with Python’s String reversal methodologies, always go with the one that is both easy to implement and faster in terms of their execution speed. In this case, we can comfortably name the Slicing approach or use of extended slice syntax as the most ideal for achieving String reversal. It is simple and only needs a few lines of code for its implementation. Moreover, our test execution simulations place it at the top of the leaderboard regarding the most efficient approaches to achieve the fastest Python’s String reversal results.

String reversal in Python should now be an element of the past and not something that still occupies your Python programming language’s to-do bucket list.

Similar Posts

Leave a Reply

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