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.
>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)