Python 2.6中的Maketrans

时间:2011-01-31 01:08:24

标签: python python-3.x

我有一个很好的小方法从字符串中删除控制字符。不幸的是,它在Python 2.6中不起作用(仅在Python 3.1中)。它声明:

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

AttributeError:type object'str'没有属性'maketrans'

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

如何改写?

2 个答案:

答案 0 :(得分:16)

在Python 2.6中,maketrans位于the string module。与Python 2.7相同。

因此,首先str.maketrans代替import string,然后使用string.maketrans

答案 1 :(得分:8)

对于此实例,字节字符串或Unicode字符串不需要maketrans

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'

或:

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'

甚至在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'

有关详细信息,请参阅help(str.translate)help(unicode.translate)(在Python2中)。