Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maketrans in Python 2.6

I have got this nice little method to remove control characters from a string. Unfortunatelly, it does not work in Python 2.6 (only in Python 3.1). It states:

mpa = str.maketrans(dict.fromkeys(control_chars))

AttributeError: type object 'str' has no attribute 'maketrans'

def removeControlCharacters(line):
   control_chars = (chr(i) for i in range(32))
   mpa = str.maketrans(dict.fromkeys(control_chars))
   return line.translate(mpa)

How can it be rewritten?

like image 597
David Avatar asked Jan 31 '11 01:01

David


2 Answers

In Python 2.6, maketrans is in the string module. Same with Python 2.7.

So instead of str.maketrans, you'd first import string and then use string.maketrans.

like image 147
Rafe Kettler Avatar answered Jan 04 '23 20:01

Rafe Kettler


For this instance, there is no need for maketrans for either byte strings or Unicode strings:

Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> delete_chars=''.join(chr(i) for i in xrange(32))
>>> '\x00abc\x01def\x1fg'.translate(None,delete_chars)
'abcdefg'

or:

Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> delete_chars = dict.fromkeys(range(32))
>>> u'\x00abc\x01def\x1fg'.translate(delete_chars)
u'abcdefg'

or even in Python 3:

Python 3.1.3 (r313:86834, Nov 27 2010, 18:30:53) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> delete_chars = dict.fromkeys(range(32))
>>> '\x00abc\x01def\x1fg'.translate(delete_chars)
'abcdefg'

See help(str.translate) and help(unicode.translate) (in Python2) for details.

like image 41
Mark Tolonen Avatar answered Jan 04 '23 22:01

Mark Tolonen