简体   繁体   English

Python - 仅使用循环删除空格

[英]Python - Remove white space using only loops

I want to remove extra spaces in a string using only for/while loops, and if statements;我想仅使用for/while循环和if语句删除字符串中的多余空格; NO split/replace/join.没有拆分/替换/加入。

like this:像这样:

mystring = 'Here is  some   text   I      wrote   '

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

print(mystring)

output:输出:

Here is some text I wrote

Here's what I tried.这是我尝试过的。 Unfortunately, it doesn't quite work.不幸的是,它并不完全有效。

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

output:输出:

Hello   my name  is  joe

My attempt doesn't remove all the extra spaces.我的尝试并没有删除所有额外的空格。

Change your code to this:将您的代码更改为:

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

    print(result)

Check that the current character and the next one are spaces, and if not , add them to a clean string.检查当前字符和下一个字符是否为空格,如果不是,则将它们添加到一个干净的字符串中。 There really is no need for an and in this case, since we are comparing to the same value在这种情况下,确实不需要and ,因为我们正在比较相同的值

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

Uses the end of result in place of lasti :使用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")

Just try this试试这个

t = "Hello my name is joe" t = "你好,我叫乔"

" ".join(t.split()) " ".join(t.split())

this will output这将输出

"Hello my name is joe" “你好,我叫乔”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM