Function doesn't remove punctuations

Solution 1:

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)

Solution 2:

I would propose to use regex and its magic to strip away the special characters:

import re

foo = "I'm a dirty string...$@@1##@*((#*@"

clean_foo = re.sub('\W+','', foo )

print(clean_foo) # Does not remove spaces (Outputs Imadirtystring1)

clean_foo2 = re.sub('[^A-Za-z0-9 ]+', '', foo)

print(clean_foo2) # Remove special chars only :D (Outputs IIm a dirty string1)