简体   繁体   中英

Python - Remove white space using only loops

I want to remove extra spaces in a string using only for/while loops, and if statements; 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

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 :

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"

" ".join(t.split())

this will output

"Hello my name is joe"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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