0

Is there some way in Python3 to remove several unwanted characters from a string, a way that is more efficient that removing each character one-by-one in a for-loop?

def RemovePunc( string ):
  punc = '\'";:.>,</?+=-_)(*&^%$#@!\`~'
  s = string
  for c in punc:
    s = s.replace(c,'')
  return s
Joseph O'Rourke
  • 4,346
  • 16
  • 25
  • 1
    Does this achieve what you want? https://docs.python.org/3/library/re.html#re.sub i.e. `re.sub('[\'";:\.>,?+=-_)(*&^%$#@!\`~]','',string)` – jpf Oct 08 '21 at 20:32
  • 3
    See [Best way to strip punctuation from a string](https://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string). – Nikolaos Chatzis Oct 08 '21 at 20:36
  • 2
    Does this answer your question? [Best way to strip punctuation from a string](https://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string) – diggusbickus Oct 08 '21 at 20:40
  • @jpf: Nice, regular expressions, `re.sub`. Excellent! – Joseph O'Rourke Oct 08 '21 at 20:41
  • @NikolaosChatzis: Thanks for that link. Again, regex lead to more efficient methods. – Joseph O'Rourke Oct 08 '21 at 20:42

0 Answers0