我还在学习 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/