python - 在 python 2.7 中翻译字符串

标签 python python-2.7

我还在学习 python,很多基础知识对我来说仍然很复杂。我刚开始使用 codewars.com,它似乎是一个很棒的工具,可以用来学习他们迄今为止设置的任何语言。唯一的缺点是他们的python只有2.7,所以部分代码必须从3.0修改才能正常工作。我现在正在解决一个问题,它希望我将数字从键盘布局转换(我认为翻译是我正在寻找的)到手机布局。所以我正在尝试将“7894561230”翻译为“1234567890”。也许这完全是错误的做法,但正如我所说,我仍在学习。这是我的代码,但它不起作用。我认为这是因为我使用的是 python 3....有什么建议吗?

from string import maketrans
def computer_to_phone(numbers):
    dict = str.maketrans('7894561230', '1234567890')
    result = numbers.translate(dict)
    return result

编辑:这是我收到的错误消息

Traceback:
   in 
   in computer_to_phone
AttributeError: type object 'str' has no attribute 'maketrans'

最佳答案

我猜问题出在线路上 -

dict = str.maketrans('7894561230', '1234567890')

你正在尝试调用 str.maketrans ,但是你没有 str 类的这种方法,在 Python 2.x 中,你应该使用 string.maketrans() 你正在导入 -

from string import maketrans
def computer_to_phone(numbers):
    dict = maketrans('7894561230', '1234567890')
    result = numbers.translate(dict)
    return result

关于python - 在 python 2.7 中翻译字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31750482/

相关文章:

python - 如何在Groupby中保留其他列的行值?

python - 当异常在实际的 'continue' 语句中时,你如何 'for'?

javascript - 使用 jQuery/AJAX 从 Cherrypy 服务器获取 JSON 数据

python - pygame.error : file not a windows. bmp 文件(看过其他类似的问题,但到目前为止没有成功)

python - 重新编码无法在 python 中以 utf-8 解码的字节

python - 在python中导入系统模块

multithreading - Python : multithreaded learning neural networks using PyBrain and Multiprocessing

python - 收到的电子邮件附件为 'noname'

python - Python中如何使用VIPS进行逻辑运算和逻辑索引?

python - django抽象模型继承导入