Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a function to remove punctuation from the left and right of a string. Ex: "_cat's_" becomes "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'))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading