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'))
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"
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'))
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"