Python 2.6中的Maketrans
我有一个很不错的方法,可以从字符串中去掉控制字符。不过不幸的是,这个方法在Python 2.6中不能用(只在Python 3.1中可以用)。它报了个错:
mpa = str.maketrans(dict.fromkeys(control_chars))
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)
那这个方法该怎么改写呢?
2 个回答
17
在Python 2.6中,maketrans
这个功能是在字符串模块里。Python 2.7也是这样。
所以,不是用str.maketrans
,你需要先用import string
来导入字符串模块,然后才能使用string.maketrans
。
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中)。