0

The following function returns a new string without the punctuations that were in the string that was passed in. Although the code works, who can it be done using the .replace() method. This part of an assignment where the hint is to use the .replace() method but strings are immutable so how do I use the .replace() method to remove punctuation? Thank you.

punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']

def strip_punct(s):
    new_s = ''
    for c in s:
        if c in punctuation_chars:
            continue
        new_s += c

    return new_s

a_string = 'He;-;l####lo.'
print(strip_punct(a_string)) # prints He-llo
mc000
  • 85
  • 1
  • 6
  • Read `replace` documentation, look at some examples. In other words, do you homework, It helps. – DYZ Feb 08 '19 at 05:58

2 Answers2

1

If you have a hint that this problem should be solved using replace() method, i suggest you to first look at the documentation for it, try it yourself and then if you still remain struck, then refer this.

>>> a_string = 'He;-;l####lo.'
>>> punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
>>> for char in punctuation_chars:
...     a_string = a_string.replace(char, '')  

Update:
If you are concerned about the speed and efficiency of the code, refer to the answer below by Alderven. There is a link in the answer which points to a more helpful resource.

taurus05
  • 2,491
  • 15
  • 28
  • 1
    Thanks. I was iterating over the characters in the string and checking if it was "in" punctuation_chars instead of iterating over the characters in the punctuation_chars list. – mc000 Feb 08 '19 at 10:55
1

The fastest way is:

table = str.maketrans({key: None for key in '\'",.!:;#@'})
print('He;-;l####lo.'.translate(table))
>>> He-llo
Alderven
  • 7,569
  • 5
  • 26
  • 38