How to remove spaces


How do you remove spaces if some presses the space bar before entering the word? All the new words will have a space if someone enters a space before the new word.


That's a tab bit advanced for this part of the course but the simplist way is to use the regex module,


from re import sub
def remove_spaces(text):
    return sub('[ ]', '', text)

This will call the sub method of the re module and it takes several arguments, the first in this case if what we are looking for a space. When we pass the space in brackets the re module will look for all spaces. The next is what we are going to replace it with which is nothing. The last part is the text we want to modify.

It is easy once you know what it going on.


Thanks zeziba,

So your example removes any space no matter where the space is?
I was researching and found . strip? I added word=word.strip() but it seems to only works for spaces at the beginning of the word. Is this correct?


Strip takes out the first instance of that character that it finds. You would have to create a loop that takes any character that is not a space otherwise.


def remove_spaces(text):
    temp = []
    for char in text:
        if char not in ' ':
    return ''.join(temp)


I should have mentioned it takes out the first instance in this case because of how strip works,


'a a a a'.strip('a')
# OUTPUT: ' a a '
# OUTPUT: ''

As you can see it does not completely sanitize the text as you would expect.


Here is a link to a good tutorial about strip()

Strip() Turtorial

That should help with any confusion on it.