顯然,我不能使用內建的string.translate
來做到這一點,但以下2個工作正常。
import string
# Construct a dictionary for required translation
translation = {}
for index, char in enumerate(string.ascii_lowercase):
translation[char] = 26 - index
# Function to translate given string
def translate(user_string):
return "".join([str(translation[c]) for c in user_string])
user_string = raw_input("Enter your string - ")
print translate(user_string)
注 - string.ascii_lowercase
給'abcdefghijklmnopqrstuvwxyz'
如果你不想翻譯轉換爲字符串,你可以做
from __future__ import print_function
import string
translation = {}
for index, char in enumerate(string.ascii_lowercase):
translation[char] = 26 - index
user_string = raw_input("Enter your string - ")
for c in user_string:
print(translation[c],end="")