Python 2.6中的Maketrans

2024-05-16 10:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很好的小方法来删除字符串中的控制字符。不幸的是,它在Python2.6中不起作用(仅在Python3.1中)。它指出:

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)

如何重写?


Tags: 方法字符串objecttypelinedictcontrolattributeerror
2条回答

对于此实例,字节字符串或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中)。

在Python 2.6中,maketransthe string module中。与Python2.7相同。

所以,你应该先使用import string,然后再使用string.maketrans,而不是str.maketrans

相关问题 更多 >