python - Python 2.6 中的 Maketrans

标签 python python-3.x

我有一个很好的小方法可以从字符串中删除控制字符。不幸的是,它在 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 中,maketransthe string module 中.与 Python 2.7 相同。

因此,您可以先导入字符串,然后使用string.maketrans,而不是str.maketrans

关于python - Python 2.6 中的 Maketrans,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4846802/

相关文章:

Python3 错误 : TypeError: Can't convert 'bytes' object to str implicitly

python - 无法在 sqlite3 python 中对关闭的游标进行操作

python - 如何根据 bool 列值压缩 Pandas 数据框?

python-3.x - Tensorflow:每次迭代运行时间增加

python - 教科书本身显示双引号,但是当我尝试时会给出SyntaxError

python - 如何让我的程序利用制表符补全?

python - 重写函数以避免 numpy.exp 中的溢出

python - 最有效的方法找到 3 个数字的最大公约数?

python - 当不是每个人都有中间名时,将名字解析为名字、中间名、姓氏

python - 使用字典和后续 .sort() 命令更正列表会显示错误的字符串顺序