Exercise 54

Write a python algorithm as a function which takes string s as input and which returns an other string obtained from s by removing all the spaces charachters at the beginning of the string s and the spaces at the end of the string s without using the lstrip() neither any predefined method. Exemple if

 s = "     Hello    "

, the function returns the string:

s = "Hello"

Solution

def removeSpace(s):
      n = len(s)
      
      # initializing the number of existing space at the end of s
      j = 0
      while(s[n-1-j]) == " ":
            j = j + 1
      s = s[:n-j]
      
      # initializing the number of existing space at the begining of s
      i = 0
      while s[i] == " ":
            i = i + 1
      s = s[i:]
      return s

# Testing algorithm 
s = "       Hello World           "
print("s with spaces : " ,"'"+ s +"'") # display : s with spaces :  '       Hello World           '
print("s without spaces:" ,"'"+ removeSpace(s)+"'") # display : s without spaces: 'Hello World'




 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 54: python program that delete multiple spaces in string a given string”

Leave a Reply