Censor - Improving code


#1


I've completed the exercise using the code posted below, but I think it looks quite clunky, and I'm sure there must be a more elegant solution. Does anybody have any advice?


def censor(text, word):
    new_text = ""
    split_text = text.split()
    for c in split_text:
        if c == word:
            x = "*" * len(word)
            new_text += x + " "
        else:
            new_text += c + " "
    
    # This part is used to remove any errant spaces at the end of the string  
    censor_text =  "".join(new_text)
    if censor_text[len(censor_text)-1] == " ":
        censor_text = censor_text[0:len(censor_text)-1]
    
    return censor_text
    
print censor('hey there you', 'you')


#2

the problem with strings in python is that they are immutable, concatenating strings means a new string with the combined result is created, not very efficient

so, instead, use new_list, append to list rather then concatenate to string and use .join() to effectively join the list into a string after the loop


#3

How about this:

def censor(text, word):
    w = "*"*len(word)
    t = text.split()
    c = 0
    for i in t:
        if i == word:
            t[c] = w
        c += 1    
    return " ".join(t)

#4

its good :slight_smile: although i would personally prefer to use range() or enumerate() to keep track of the indexes


#5

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