Censor with While Loop


#1




I'm trying to make this code work using a while loop. BUT
This code returns "*** * *** * * " instead of "*** *** ***" for the function input censor("hey hey hey", "hey). Help on this will be much appreciated.


def censor(text, word):
    length=int(len(word))
    text=text.split()
    cypher=""
    new_text=" "
    for word in text:
        if word==word:
            while length>0:
                for c in word:
                    cypher+='*'
                    length-=1
                    new_text=new_text.join(cypher)+" "
        
        return new_text


#2

could you explain why you use .join()? it is a method for joining a list into a string, new_text is already a string


#3

Because the concatenation methods i tried before this, only returned 3 *** instead of the required 9, only by using .join was i able to get the function to return all 9 *** *** *** although the spacing is off. I'm unsure about how to fix it. I wanted to force myself to solve using the while loop...if it's possible.


#4

but then use the while loop as main loop:

def censor(text, word):
    length=int(len(word))
    text=text.split()
    cypher=""
    new_text=""
    x = 0
    while x < len(text):
        # do something
       x += 1

you currently have 3 loops, this will cause trouble


#5

You're right I removed both the for loops and the program had the same output. For now I will solve using a for loop and come back to revisit it. Thanks for your help.


#6

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