簡體   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