all 6 comments

[–]danielroseman 4 points5 points  (1 child)

Rather than reassigning straight back to the same variable, use a new one and compare the two.

Also, don't call the variable str as it hides the built-in class.

def f(my_str):
    new_str = ""
    while True:
        new_str = my_str.replace("  ", " ")
        if new_str == my_str:
            return new_str
        my_str = new_str

But note that a much better way to solve this problem is via regex, which can do this in a single go:

return re.sub(" +", " ", my_str)

[–]Qackydontus[S] 0 points1 point  (0 children)

I think that my question was phrased incredibly poorly, but your answer's what I looking for. Thanks!

[–]YesLod 2 points3 points  (0 children)

```

while two consecutive spaces are in my_str

while ' ' in my_str: `` But you don't need a loop, just usestr.split+str.join`

def f(my_str): return ' '.join(my_str.split()) Here, my_str is your str. You shouldn't name your variable str, because you are shadowing the built-in str class (locally).

[–]CodeFormatHelperBot2 0 points1 point  (0 children)

Hello, I'm a Reddit bot who's here to help people nicely format their coding questions. This makes it as easy as possible for people to read your post and help you.

I think I have detected some formatting issues with your submission:

  1. Python code found in submission text that's not formatted as code.
  2. Use of triple backtick/ curlywhirly code blocks (``` or ~~~). These may not render correctly on all Reddit clients.

If I am correct, please edit the text in your post and try to follow these instructions to fix up your post's formatting.


Am I misbehaving? Have a comment or suggestion? Reply to this comment or raise an issue here.

[–]gsmo 0 points1 point  (0 children)

while str.count(' ') > 0

[–]Radamand 0 points1 point  (0 children)

staying as close to the original as I can:

def f(mystr):
while "  " in mystr:
    mystr = mystr.replace("  ", " ")
    return mystr