Home > Software engineering >  Script on Python, that censures bad words with "*" signs
Script on Python, that censures bad words with "*" signs

Time:07-30

I want to write a function that will take a string from the user as a parameter, and then will replace the words in the string from the tuple of forbidden words with asterisks. There must be as many asterisks as there are characters in the substring that is included in the tuple of forbidden words.

def censure(sent):
    bad = ('whatever', 'bad', 'word', 'you', 'can', 'think', 'of')
    st = str(sent).lower()
    for item in bad:
        if item in st:
            st = st.replace(item, '*' * len(item))
    return st

chat = input('Type text with bad words:\n')
print(censure(chat))

It works good, BUT one problem: It returns user string on lower case. But i wans save the original user casing. I made it lower to compare with items in bad words tuple. Help to save original casing in result!

CodePudding user response:

One slightly botched, but very open and functional version of doing this would be:

def censure(sent):
    bad = ('foo', 'bar', 'zoo')
    st = str(sent).lower()
    org_st = str(sent) # creape a copy of st that has caps
    for item in bad:
        if item in st:
            st = st.replace(item, '*' * len(item))
    st = list(st)           #
    org_st = list(org_st)   # make both items lists

    runs = -1
    for char in st:
        runs =1
        if char == "*":
            org_st[runs] = "*" # replace any position in org_st with * if st has that possition as *

    return "".join(org_st) # returns list as a string

chat = input('Type text with bad words:\n')
print(censure(chat))

This works by utilizing another variable and the .join() function

  • Related