我有一个很好的小方法来删除字符串中的控制字符。不幸的是,它在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)
如何重写?
对于此实例,字节字符串或Unicode字符串不需要
maketrans
:或:
甚至在Python 3中:
有关详细信息,请参见
help(str.translate)
和help(unicode.translate)
(在Python2中)。在Python 2.6中,
maketrans
在the string module中。与Python2.7相同。所以,你应该先使用
import string
,然后再使用string.maketrans
,而不是str.maketrans
。相关问题 更多 >
编程相关推荐