繁体   English   中英

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

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

我想编写将删除字符串中无关空格的代码。 单词之间的任何超过 1 个空格都是无关空格。 我想删除这些空格,但在单词之间保留 1 个空格

我编写的代码将删除开头和结尾的空格,但我不确定是否要删除中间空格但保留 1 。

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

所以这就是我的代码现在所做的

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

我想要它做的是:

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

我该怎么做?

它是这样工作的:

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

您可以使用re.sub将任意数量的空格替换为单个空格:

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

你可以做:

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

您可以使用内置的字符串方法:

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

Output 将是:

cats go meow

暂无
暂无

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

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