Reverse String Program

Reverse String program


  Machine Learning in Python

Summary : A simple program in Python to reverse a string. We will learn more about Strings in python and how to manipulate them.

Very much like how you can put an integer in a variable, you can also put strings in a variable. Just like how we divide or multiply numbers, we can also manipulate a string, like concatenate or split strings, find out the length of a string etc. 

Program Logic

In this program, we will reverse a string, not literally reverse it, but reverse the words. For example “United States of America” should be reversed as “America of States United” . We are reversing the order of the words in the string.

Source code :

user_input = input ( "Enter a string to reverse - ")
user_input = user_input.split ( " ")

user_output = ""
str_len = len(user_input)

while ( str_len >= 1 ):
    user_output = user_output + " " + user_input[str_len - 1]
    str_len = str_len - 1
    
print ( user_output)

Syntax Explanation

String split

The first thing we have to do is to get the input string from the user and split it into its constituent words. In order to do that, we can use the standard python string function – split().

user_input = input ( "Enter a string to reverse - ")
user_input = user_input.split ( " ") 

This is the first time we are using a Class function, rather than a standalone function. For example, we have used the input () function or the print () function in a standalone way – meaning, we just specify the function along with its required parameters. In the case of split function, we are using it as a function of the string user_input. That is why, we are using the . ( dot ) operator. This is easy to understand if you have Object Oriented programming background like C++ or Java or Javascript. If you don’t have that experience that’s fine too – Just understand that the split function is used in the context of a string.

So, when you write

user_input = input ( "Enter a string to reverse - ") 

user_input is not just a variable. It also has certain properties associated with it.You can better understand this when we do the following.

i = 100
print ( "i is a variable of type ", type(i))
name = "Ajay"
print ( "name is a variable of type ", type(name))
------output--------
i is a variable of type  <class 'int'> 
name is a variable of type  <class 'str' 

So, depending on the value that is assigned to a variable, the type of variable is dynamically determined by python at run-time. And depending on the value assigned to the variable, python associates certain properties and methods to it. Think of these as capabilities associated with the variable. These methods can be accessed via the dot (.) operator. Without understanding object oriented python, this is how far we can go in understanding these methods. Nothing to worry though – this does not affect our understanding of Data Science of Machine Learning.

The method split() takes in an input parameter – a character or string based on which we can do the split. In our case, we want to split the sentence into its words. So, the split criteria is a blank character.

We can understand this better if we print the resultant splits.

user_input = user_input.split ( " ") 
print ( user_input )
----------output--------------------
['united', 'states', 'of', 'america'] 

The variable user_input now stores the words of the string that the user has input in a list. We will learn more about lists later, when we learn data structures in python. But for now, think of a list as a variable that holds a bunch of values, not just one ( like a typical variable does ).

Now, that we have done the split, we need to reverse the order of these words and re-form the string again.

This is where indexing helps.  

List Index

We know that a list is a variable that holds a bunch of values. For example, in our case the list user_input holds a list of all the words from the string. Can we get each of these words separately ? Yes, we can – that is where an index comes in.

Initially, user_input variable was pointing to a string.

After the split, the same variable is not pointing to a list.

And each word of the list can be access individually.

To access the individual elements of a list, you use square brackets. So, user_input[0] would point to the first word – “United” and user_input[1] to “States” and so on. In python indexing starts at 0, not at 1 ( Like C or java ).  

String or List Length

The length of a string can be found using the standard python function len () . Similarly, the length of a list can be found using the same len() function. Why do we need to do that in this case ? We want to reverse the words in the string right ? First we have split up the string into its words. Now, we need to join them in reverse order – meaning, we have to start from the last word. But, how do we find out how many words are there in the list ? That is where the len() function is helpful.

str_len = len(user_input) 

String Concatenation

Now, we have to start rebuilding the string in reverse order – starting with the last word.

while ( str_len >= 1 ):    
    user_output = user_output + " " + user_input[str_len - 1]    
    str_len = str_len - 1 

This logic should sound simple. We are using the indexing capability of list to extract all the words from the end and concatenating to the blank string user_output until we hit the first word in the list.

%d bloggers like this: