David David - 1 year ago 67
Python Question

Removing control characters from a string in python

I currently have the following code

def removeControlCharacters(line):
i = 0
for c in line:
if (c < chr(32)):
line = line[:i - 1] + line[i+1:]
i += 1
return line

This is just does not work if there are more than one character to be deleted.

Answer Source

You could use str.translate with the appropriate map, for example like this:

>>> mpa = dict.fromkeys(range(32))
>>> 'abc\02de'.translate(mpa)