How to remove string control characters (\n \t \r) in python

Published: April 26, 2018

DMCA.com Protection Status

To remove control characters such as \n \t \r characters, a first approach will be to use a regex:

>>> import re
>>> s = "Salut \n Comment ca va ?"
>>> regex = re.compile(r'[\n\r\t]')
>>> s = regex.sub(" ", s)
>>> s
'Salut   Comment ca va ?'

Another approach using translate:

>>> import string
>>> s = "Salut \n Comment ca va ?"
>>> t = string.maketrans("\n\t\r", "   ")
>>> s = s.translate(t)
>>> s
'Salut   Comment ca va ?'
>>>

Note: see Deleting specific control characters(\n \r \t) from a string
for a discussion about the speed of those two approaches.

References