DEV Community

subash
subash

Posted on

Remove unwanted space in through forloop in python

How to remove extraspace between the word

sentence = 'how           are           you'
result = ""
first_space = True
for letter in sentence:
    if letter !=" ":
        result +=letter 
        first_space = True
    elif first_space==True:
        result += " "
        first_space = False
print(result)

Enter fullscreen mode Exit fullscreen mode

OUTPUT:

Explanation :

First we create sentence variable that have the content "how are you" with extra space , we want to remove extra space , that's the purpose of this program,
we create another variable that's called result that have empty string to store correct sentences without extra space.
we need to create one more variable to store boolean value

We create for loop :

for letter in sentence:
Enter fullscreen mode Exit fullscreen mode

Here sentence we already know that is variable what we created , here what will happen is each letter in sentence variable also include space store store in letter variable , like first store 'h' and then second 'o' and then 'w', this loop will run until finish the character of sentences.

 if letter !=" ":
        result +=letter 
        first_space = True
Enter fullscreen mode Exit fullscreen mode

here what was happened is letter have the first character of sentences that is h, now this condition will letter not equal to space(" "), if true result variable keep that character and this condtion last we gave first_space we put again true this will help to store the first empty space inbetween the word , until w it will collect , and then first space will come in letter then if condition will false , program will enter the elif part,

    elif first_space==True:
        result += " "
        first_space = False
Enter fullscreen mode Exit fullscreen mode

here first space is true so space will store the result , and we gave firs_space = false , here after this not store space again , because if and elif both conditions will false, when letter variable return any spelling then again if condition is true and then first_space will true , again store first space , and first_space will false etc

this program will remove all the extra space,

Top comments (0)