繁体   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