Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove spaces in a string using a loop in python?

def onlyLetters(s):
    for i in range(len(s)):
        if s[i] == " ":
           s = s[:i] + s[i+1:]
           return s
        return s

Why is my above loop not working? It seems like it's only doing it once.

For example, if i have the string "Hello how are you", it's returning "Hellohow are you". I want it to check the string again and remove another space, and keep doing it until there are no spaces left. How do I fix this code?

like image 246
Razi Syed Avatar asked Sep 23 '26 16:09

Razi Syed


1 Answers

Your code is stopping after the first space is replaced because you've told it to. You have return s inside the loop, and when that is reached, the rest of the loop is abandoned since the function exits. You should remove that line entirely.

There's another issue though, related to how you're indexing. When you iterate on range(len(s)) for your indexes, you're going to go to the length of the original string. If you've removed some spaces, however, those last few indexes will no longer be valid (since the modified string is shorter). Another similar issue will come up if there are two spaces in a row (as in "foo bar"). Your code will only be able to replace the first one. After the first space is removed, the second spaces will move up and be at the same index, but the loop will move on to the next index without seeing it.

You can fix this in two different ways. The easiest fix is to loop over the indexes in reverse order. Removing a space towards the end won't change the indexes of the earlier spaces, and the numerically smallest indexes will always be valid even as the string shrinks.

def onlyLetters(s):
    for i in range(len(s)-1, -1, -1): # loop in reverse order
        if s[i] == " ":
            s = s[:i] + s[i+1:]
    return s

The other approach is to abandon the for loop for the indexes and use a while loop while manually updating the index variable:

def onlyLetters(s):
    i = 0
    while i < len(s):
        if s[i] == " ":
            s = s[:i] + s[i+1:]
        else:
            i += 1
    return s
like image 185
Blckknght Avatar answered Sep 26 '26 07:09

Blckknght



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!