简体   繁体   English

删除 Python 中字符串中多余空格并在单词之间保留 1 个空格的代码

[英]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.单词之间的任何超过 1 个空格都是无关空格。 I want to remove those spaces but keep 1 space in between words我想删除这些空格,但在单词之间保留 1 个空格

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.我编写的代码将删除开头和结尾的空格,但我不确定是否要删除中间空格但保留 1 。

#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:您可以使用re.sub将任意数量的空格替换为单个空格:

>>> 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: output:

Cats go meow

You can use built-in string methods:您可以使用内置的字符串方法:

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

Output will be: Output 将是:

cats go meow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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