KittyWhale
KittyWhale

Reputation: 89

Code to remove extraneous spaces in a string in Python and keep 1 space between words

I want to write code that will remove extraneous spaces in a string. Any more than 1 space in between words would be an extraneous space. I want to remove those spaces but keep 1 space in between words

I've written code that will remove spaces at the beginning and the end but I'm not sure for to make it remove the middle spaces but keep 1 there.

#Space Cull
def space_cull(str):
  result = str 
  result = result.strip()
  return result

So this is what my code does right now

space_cull('    Cats   go   meow   ')
#It would return
'Cats   go   meow'

What I want it to do is this:

space_cull('    Cats   go    meow')
#It would return
'Cats go meow'

How should I do this?

Upvotes: 1

Views: 1742

Answers (4)

Alexall
Alexall

Reputation: 423

you can do :

txt = '    Cats   go   meow   '

def space_cull(string):

    word = string.split(" ")
    result = ""
    for elem in word:
        if not elem == '':
            result += str(elem) + ' '
    return result.strip()

print(space_cull(txt))

output:

Cats go meow

Upvotes: 0

Seysen
Seysen

Reputation: 134

You can use built-in string methods:

x = "  cats    go    meow     "
print(*x.strip().split())

Output will be:

cats go meow

Upvotes: -1

JBGreen
JBGreen

Reputation: 544

You can use re.sub to replace any number of spaces with a single space:

>>> import re
>>> re.sub(r"\s+", " ", "foo    bar")
"foo bar"

Upvotes: 2

Nils
Nils

Reputation: 930

It works like this:

sentence = '    Cats   go   meow   '
" ".join(sentence.split())

Upvotes: 5

Related Questions