-1

The aim of the code is to go through a string using a for loop and remove certain punctuations specifically (“,”,“.”,“?”,“!”, “;”,“:”) with the statement if c in (“,”,“.”,“?”,“!”, “;”,“:”) included. So for I have tried using stringting.replace(stringting[i],"") in the 5th line of the code below and then I tried using stringting.translate() in line 5 with no luck. Why is it not working?

    def removePun(stringting):
      new_string = ""
      for i in range (0,len(stringting)):
        if stringting[i] in (",",".","","?",";",":"):
          new_string = stringting.translate({ord(stringting[i]): None})
      return new_string
ddejohn
  • 8,775
  • 3
  • 17
  • 30
Dre
  • 1

2 Answers2

1

There are numerous approaches to this problem. Try this,

def remove_punctuation(string):
    result = ""
    for punc in ",:;!.?":
        result = result.replace(punc, "")
    return result

If you want to use str.translate() you need to make a translation table:

t = str.translate("", "", ",:;!.?")
some_word.translate(t)

Using str.translate is ideal in the case of single-character removals. I go into more details for a duplicate of this question here.

ddejohn
  • 8,775
  • 3
  • 17
  • 30
1

Instead of testing if a character is in the tuple and then removing it, it would be simpler to test if it is not in the tuple and then add it to the result - or, better, use a list comprehension which only takes one line of code. So:

punctuation = (",",".","","?",";",":")
def removePun(string):
    return "".join([c for c in string if c not in punctuation])
Lecdi
  • 2,189
  • 2
  • 6
  • 20
  • Note that `str.join` accepts a generator, no need to create an interim `list` in memory. It's also much more efficient to loop through the characters to remove and use `str.replace`, as a naive filtering accumulator must traverse the entire string (consider a large input string, versus a relatively small list of characters to remove). – ddejohn Oct 17 '21 at 19:13
  • @ddejohn true, although, a list will always be created (or else join couldnt be implemented efficiently – juanpa.arrivillaga Oct 17 '21 at 19:22