DEV Community

Cover image for REMOVE SPACES FROM A STRING
Vinoth Kumar
Vinoth Kumar

Posted on

REMOVE SPACES FROM A STRING

Q1) REMOVE AN UNWANTED FRONT SPACE IN A STRING

sentence = '              today is my first day at the new job.'
space =' '
front_space= True
for letter in sentence:
    if letter == space and front_space == True:
        continue
    else:
        front_space = False
        print(letter,end='')
Enter fullscreen mode Exit fullscreen mode

OUTPUT :

today is my first day at the new job.

Q2) REMOVE AN UNWANTED BACK SPACES IN A STRING

sentence = '"today is my first day at the new job.              "'
i = len(sentence) - 1
end = 0
while i >= 0:
    if sentence[i] == '':
        i-=1
        continue
    else:
        end = i
        break
    i-=1
i = 0
while i <= end:
    print(sentence[i],end ='')
    i+=1
Enter fullscreen mode Exit fullscreen mode

OUTPUT :

today is my first day at the new job.

Q3) REMOVES UNWANTED SPACES IN BETWEEN THE WORDS :

sentence ='today     is      friday'
previous_letter = True
for letter in sentence:
    if letter !=' ':
        print(letter,end='')
        previous_letter = True
    else:
        if letter == ' ' and previous_letter == True:
            print(letter,end='')
            previous_letter = False
Enter fullscreen mode Exit fullscreen mode

OUTPUT :

today is friday

Top comments (0)