Create a function to remove punctuation from the left and right of a string. Ex: "_cat's_" becomes "cat's"

Question:

I already have started the function as seen below. At first i didn’t include the .strip() module but after research I did because i thought it would remove the characters from the beginning and end of the string.

import string

def detect_word(source, word):
    source = source.strip().lower()
    word = word.strip().lower()
    split_source = source.split()
    if word in split_source:
        return True
    else:
        return False

I created 3 test cases upon which the first 2 should have returned true and the last one false. However, my first test case always fails and returns false instead of true. Here they are.

t1 = "I have a cat."
t2 = "My cat is orange"
t3 = "Everything is a catastrophe."

print(detect_word(t1, 'cat'))
print(detect_word(t2, 'cat'))
print(detect_word(t3, 'cat'))
Asked By: Sukwha

||

Answers:

str.strip() strips whitespace by default. Pass string.punctuation as an argument to make it strip punctuation instead.

>>> "_cat's_".strip()
"_cat's_"
>>> "_cat's_".strip(string.punctuation)
"cat's"
Answered By: Samwise
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.