How can i remove unwanted spaces from the string using enumerate function and for loop

Viewed 142

i have this code but it is not working.. i don't know what's wrong in this code

djtext = "g o d  i s   gre at"
analyzed = ""
for index, char in enumerate(djtext):
    if not(djtext[index] == " " and djtext[index+1]==" "):
      analyzed = analyzed + char
print(analyzed)

I want the output like this

god is great

But it gave me this output

g o d i s gre at

2 Answers

You can achieve the result you want by using split to split the string on two spaces and then join the parts again with the spaces removed

' '.join(word.replace(' ', '') for word in djtext.split('  ') if word)

Consider this alternative solution using regular expressions:

import re
djtext = "g o d  i s   gre at"
analyzed = re.sub(r' (.)', lambda x: x.group(1), djtext)
print(analyzed)

This matches a space followed by any character, and replaces all such sequences with just the character that was matched.

This gives the desired output:

god is great

If you want to stick with your original approach, then you need to add an extra condition to make it work. Your original code covers one cases (reducing multiple spaces) but misses the other cases (removing the unnecessary spaces).

The following version is the correct version of your code. It adds the condition char == " " and djtext[index - 1] != " ", which just checks that if the current character is a space, the character before it is not also a space. In such a case, you wouldn't want to keep the space.

djtext = "g o d  i s   gre at"
analyzed = ""
for index, char in enumerate(djtext):
    if not((char == " " and djtext[index + 1] == " ") or (char == " " and djtext[index - 1] != " ")):
        analyzed += char
print(analyzed)

Side note: for readability, I've switched djtext[index] to char and analyzed = analyzed + char to analyzed += char.

Related