Python 2.6中的Maketrans

Dav*_*vid 9 python python-3.x

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

mpa = str.maketrans(dict.fromkeys(control_chars))
Run Code Online (Sandbox Code Playgroud)

AttributeError:类型对象'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)
Run Code Online (Sandbox Code Playgroud)

怎么改写?

Raf*_*ler 16

在Python 2.6中,maketrans是在字符串模块中.与Python 2.7相同.

所以不是str.maketrans,你首先import string然后使用string.maketrans.


Mar*_*nen 8

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

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'
Run Code Online (Sandbox Code Playgroud)

要么:

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'
Run Code Online (Sandbox Code Playgroud)

甚至在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'
Run Code Online (Sandbox Code Playgroud)

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