简体   繁体   English

在python 2.7中翻译字符串

[英]Translate strings in python 2.7

I'm still learning python and a lot of basics are still complicated to me. 我仍在学习python,很多基础知识对我来说仍然很复杂。 I just started out using codewars.com, and it seems like an awesome tool to learn any of the languages they have set up so far. 我刚开始使用codewars.com,它似乎是一个很棒的工具,可用来学习他们迄今为止设置的任何语言。 The only downside is their python is only 2.7, so some of the code has to be modified from 3.0 to work properly. 唯一的缺点是他们的python只有2.7,因此某些代码必须从3.0进行修改才能正常工作。 I'm working on one problem now that wants me to convert (I think translate is what I'm looking for) numbers from the keyboard layout to the phone layout. 我现在正在处理一个问题,希望我将数字从键盘布局转换为电话布局(我想翻译是我要找的东西)。 So I'm trying to translate '7894561230' to '1234567890'. 所以我正在尝试将'7894561230'转换为'1234567890'。 Maybe this is entirely the wrong way to go about doing it, but as I said, I'm still learning. 也许这完全是错误的做法,但正如我所说,我仍在学习。 Here is the code I have, but it's not working. 这是我的代码,但是没有用。 I think it's because I'm using python 3.... Any suggestions? 我认为这是因为我正在使用python 3。...有什么建议吗?

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

EDIT: Here's the error message I'm getting 编辑:这是我收到的错误消息

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

I am guessing the issue comes from line - 我猜问题出在网上-

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

You are trying to call str.maketrans , but you there is not such method for str class , in Python 2.x , you should make use of the string.maketrans() you are importing instead - 您正在尝试调用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM