Wednesday, October 21, 2020

Solution Exercise 54: python algorithm to delete multiple spaces in string

Exercise 54

Write a python program as a function which takes as a parameter a string s and which returns another string obtained from s by removing the spaces 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
``"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'``````

my-courses.net