How to remove spaces


#1

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.


#2

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

Example:

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.


#3

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?


#4

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.

Example:

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

EDIT:

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

EXAMPLE:

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

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


#5

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

Strip() Turtorial

That should help with any confusion on it.