Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace punctuation in a string in Python?

Tags:

I would like to replace (and not remove) all punctuation characters by " " in a string in Python.

Is there something efficient of the following flavour?

text = text.translate(string.maketrans("",""), string.punctuation) 
like image 236
register Avatar asked Sep 15 '12 13:09

register


1 Answers

This answer is for Python 2 and will only work for ASCII strings:

The string module contains two things that will help you: a list of punctuation characters and the "maketrans" function. Here is how you can use them:

import string replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation)) text = text.translate(replace_punctuation) 
like image 154
Benji York Avatar answered Oct 24 '22 08:10

Benji York