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

Function doesn't remove punctuations

I’m new with python and I’m having problems with my function. I need to remove punctuation symbols from the string, so, the simplest thing I could think up is to loop the string and replace the punctuation for an empty character; though the function actually does remove full stops, it doesn’t do it with the comma. I tried to debug it and it recognises the comma in the condition, but it doesn’t remove it.

The code is this:

string = "the Zen of Python, by Tim Peters. beautiful is better than ugly. explicit is better than implicit. simple is better than complex."


def remove_punctuation(string):

    punctuation = [",", "."]

    for char in string:
        if char in punctuation:
            raw_string = string.replace(char, "")

    return raw_string

print(remove_punctuation(string))

The thing is the exercise says I can only use replace or del, so I’m a bit restricted with this.

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 :

solution number 1:

with replacing:

def remove_punctuation(string):
    punctuation = [",", "."]

    for char in punctuation:
        string = string.replace(char, "")

    return string


string = "the Zen of Python, by Tim Peters. beautiful is better than ugly." \
         " explicit is better than implicit. simple is better than complex."

print(remove_punctuation(string))

basically we do the replacing one per each character in punctuation.

solution number 2:

If you wanna get better performance you can .translate the string:

def remove_punctuation(string):
    punctuation = [",", "."]
    table = str.maketrans(dict.fromkeys(punctuation))
    return string.translate(table)

In translation, each key that has the value of None in the table, will be removed from the string. fromkeys will create a dictionary from an iterable and put None as their values (it’s the default value)

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