Skip to main content
 首页 » 编程设计

Python之仅使用循环删除空格

2025年05月04日18bjzhanghao

我只想使用 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)