Python - 仅使用循环删除空格

时间:2017-03-29 20:39:45

标签: python

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

我的尝试不会删除所有额外的空格。

4 个答案:

答案 0 :(得分:4)

将您的代码更改为:

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

    print(result)

答案 1 :(得分:1)

检查当前字符和下一个字符是否为空格,如果不是,请将它们添加到干净的字符串中。在这种情况下确实不需要and,因为我们正在比较相同的值

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

答案 2 :(得分:1)

使用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")

答案 3 :(得分:-1)

只需尝试

t =“你好,我叫乔”

“” .join(t.split())

这将输出

“你好,我叫乔”

相关问题