Banned Word Checker

Write a Python program that takes a string and raises an exception if it contains any banned words from a predefined list.

Example 1:

Input: String: "This is a banned word.", Banned words: ["banned", "prohibited"] 
Output: "Error: String contains a banned word."

Example 2:

Input: String: "This is a safe sentence.", Banned words: ["banned", "prohibited"] 
Output: "String checked successfully."

Use Python’s string methods to split the string into words and check each word against the banned list.

def check_string(string, banned_words):
    words = string.lower().split()
    for word in words:
        if word in banned_words:
            raise Exception("Error: String contains a banned word.")
    return "String checked successfully."

print(check_string("This is a banned word.", ["banned", "prohibited"]))  # Output: "Error: String contains a banned word."
print(check_string("This is a safe sentence.", ["banned", "prohibited"]))  # Output: "String checked successfully."

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!