Censor Dispenser: basic logic understanding -- comment feedback

Hey folks,

In the Censor Dispenser project we need to create code that censors specific word(s).

Can someone look over the lines of code below and tell me if my comments accurately reflect the logic of each line?

def censor_two(input_text, censored_list):  # create function with meaningful and descriptive argument names.
    for word in censored_list: # basic names again, picking out each word in our pre-defined censorship list.
        censored_item = ""  # creating a string holder that's empty.
        for x in word:   # for every element (letter) in every word: 
            if x == '':  # if the element is empty...
                censored_item += '' # ... add an empty element to our string holder (so basically add nothing).
            else: # otherwise
                censored_item += "X" # for every element add the string 'X'
        input_text = input_text.replace(word, censored_item) # at the end of every nested for loop, (so for
        # every word replace the word with it's equivalent X string (in length).
    return input_text # once we've iterated over every word and replaced it with its X equivalent, return final text.

print(censor_two(email_two, proprietary_terms))

Specifically, the part starting from line 3 to line 6 is a bit weird to me. It seems like we’re creating an empty variable and in that first (and only) IF statement are just adding nothing? If that is the case I understand why and how it works, but it is really the most elegant way to do it?

Edit 1: moreover, I just realize that on line 5 it’s x == 3, not x = 3, how come?

For some reason this part has me perplexed since yesterday. Any clarification on that point would be greatly appreciated.

Concatenating '' to another string leaves you with a string identical to the one you already have.
Consider not doing it, that would have the same outcome. hold down backspace for a bit.

You have another piece of code nearby that conditionally concatenates 'X' with another string.
You’ve got:

if something then do nothing else do stuff

change that to:

if not something then do stuff

Not sure what code you’re talking about but == and = do completely different things, which does what and which behaviour did you require? Use that one. They’re not subtly different so you don’t need help figuring out which one you meant. They’re totally separate, no overlap.

str.replace does not care about words in the slightest, it cares about substrings, if you for example replace a then it will not only remove the word a, but also all letters a even if they are part of other words

1 Like

Thank you, that was helpful.

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