Remove Tabs in a String

In this lesson, we will learn how to remove tabs from a string using recursion.

What does “Removing Tabs from a String” mean?

Our task here is to remove all spaces, i.e., the character \t or " " from a string.

Removing spaces from a string
Removing spaces from a string

Implementation

Press + to interact
def remove(string):
# Base Case
if not string:
return ""
# Recursive Case
if string[0] == "\t" or string[0] == " ":
return remove(string[1:])
else:
return string[0] + remove(string[1:])
# Driver Code
print(remove("Hello\tWorld"))

Explanation

After removing tabs from a null string "" we will get a null string "". Therefore, this can be our base case. For the recursive case, we check whether the current element is "\t":

  1. If the current element is "\t" we discard it and call another instance of the function but with that element removed.
  2. If the current element is not "\t" we append it to the string we are going to output in the end and call another instance of the function but with that element removed.

Note: The string Hello World is the same as the string Hello\tWord. This means that \t and " " are interchangeable. However, pay close attention to the fact that " " is not the same as "". One is a space character and the other is a null string

Let’s have a look at the sequence of function calls;


Let’s have a look at another example of string manipulation with recursion in the next lesson.