我有一个很好的小方法可以从字符串中删除控制字符。不幸的是,它在 Python 2.6 中不起作用(仅在 Python 3.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)
如何重写?
最佳答案
在 Python 2.6 中,maketrans
在 the string module 中.与 Python 2.7 相同。
因此,您可以先导入字符串
,然后使用string.maketrans
,而不是str.maketrans
。
关于python - Python 2.6 中的 Maketrans,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4846802/