[英]Translate strings in 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.