Home > front end >  How does one go about removing a character in a string using a for loop in python 3?
How does one go about removing a character in a string using a for loop in python 3?

Time:10-18

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related