簡體   English   中英

Python - 僅使用循環刪除空格

[英]Python - Remove white space using only loops

我想僅使用for/while循環和if語句刪除字符串中的多余空格; 沒有拆分/替換/加入。

像這樣:

mystring = 'Here is  some   text   I      wrote   '

while '  ' in mystring:
    mystring = mystring.replace('  ', ' ')

print(mystring)

輸出:

Here is some text I wrote

這是我嘗試過的。 不幸的是,它並不完全有效。

def cleanupstring(S):
    lasti = ""
    result = ""

    for i in S:
        if lasti == " " and i == " ":
            i = ""

        lasti = i    
        result += i    

    print(result)


cleanupstring("Hello      my name    is    joe")

輸出:

Hello   my name  is  joe

我的嘗試並沒有刪除所有額外的空格。

將您的代碼更改為:

    for i in S:
        if lasti == " " and i == " ":
            i = ""
        else:
            lasti = i    
        result += i    

    print(result)

檢查當前字符和下一個字符是否為空格,如果不是,則將它們添加到一個干凈的字符串中。 在這種情況下,確實不需要and ,因為我們正在比較相同的值

def cleanWhiteSpaces(str):
  clean = ""
  for i in range(len(str)):
    if not str[i]==" "==str[i-1]:
      clean += str[i]
  return clean

使用result的結尾代替lasti

def cleanupstring(S):
    result = S[0]

    for i in S[1:]:
        if not (result[-1] == " " and i == " "):
            result += i

    print(result)


cleanupstring("Hello      my name    is    joe")

試試這個

t = "你好,我叫喬"

" ".join(t.split())

這將輸出

“你好,我叫喬”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM