简体   繁体   中英

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?

It works like this:

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

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"

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

You can use built-in string methods:

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

Output will be:

cats go meow

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM