Home > Enterprise >  removing punctuation from the word with function. Language: python
removing punctuation from the word with function. Language: python

Time:09-13

I am trying to define a function which will take one parameter, a string which represents a word, and removes characters considered punctuation from everywhere in the word. I am trying to use the .replace() function only.

For example: if the word is " inc#credi!ble" it will return "incredible". However, the one I am writing now is replacing only one parameter. Below is the code:

punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
def strip_punctuation(word):
   for char in word:
       if char in punctuation_chars: 
           char_without_punct = word.replace(char,"",)
   return char_without_punct

y = strip_punctuation("#incr!edible") print(y)

CodePudding user response:

I suggest a regex replacement here:

import re

punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
regex = r'(?:'   r'|'.join([re.escape(x) for x in punctuation_chars])   r')'

def strip_punctuation(word):
    word = re.sub(regex, '', word)
    return word

inp = "inc#redi!ble"
print(strip_punctuation(inp))  # incredible

CodePudding user response:

Try literally the opposite of what you said. Make a new word of the characters that are not punctuation.

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


def strip_punctuation(word):
    word_without_punctuation = ''
    for char in word:
        if char not in punctuation_chars:
            word_without_punctuation  = char
    return word_without_punctuation

However, it's better not to build your own bicycle and use str.isalnum() function:

def strip_punctuation(word: str) -> str:
    word_without_punctuation: str = ''
    char: str
    for char in word:
        if char.isalnum():
            word_without_punctuation  = char
    return word_without_punctuation
  • Related