Problem with for loops


#1

my code

this is the censor problem ,i wrote a for loop to solve this problem , but i noticed that that code is buggy , so after some debugging i realized that the line [ i += len(word) ] does not work as i expected , and i don’t understand why , i wanted to go around this so i replaced the for loop with a while loop ,and the code worked just fine , is there any smart way to do the same thing with for loops ? :smiley:


#2

lets do an example:

x = [1,2,3,4,5]
for i in x:
    print "before: {:d}".format(i)
    i += 3
    print "after: {:d}".format(i)

we can make changes to i, but the for loop will simply assign the next value of the list to i. Which is why your solution doesn’t work

this is different then while, where we can manually change the value of the loop iterator, even from within the loop


#3

so , i can’t solve this problem using for loops ?


#4

i don’t know what you can and can’t do :wink:

jokes aside, its possible to solve this problem with a for loop, but you will need a slightly different approach.

you could do something like:

for character in text:
   current_word = ""
   if character == " ": # check if character is space
       if current_word == word:
           # we need to censor
           current_word = ""
       else:
           current_word += character

or you could find the built-in function which allows for splitting the sentence into separate words.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.