似乎无法弄清楚如何用数字替换字母。例如
让我们说
'a' , 'b' and 'c' should be replaced by "2".
'd' , 'e' and 'n' should be replaced by "5".
'g' , 'h' and 'i' should be replaced by "7".
我要替换的字符串是again。我想要得到的输出是 27275。 这些数字的结果应该是字符串。
到目前为止我有:
def lett_to_num(word):
text = str(word)
abc = "a" or "b" or "c"
aef = "d" or "e" or "n"
ghi = "g" or "h" or "i"
if abc in text:
print "2"
elif aef in text:
print "5"
elif ghi in text:
print "7"
^我知道上面是错的^
我应该写什么功能?
请您参考如下方法:
从字符串使用 maketrans:
from string import maketrans
instr = "abcdenghi"
outstr = "222555777"
trans = maketrans(instr, outstr)
text = "again"
print text.translate(trans)
输出:
27275
string 模块的 maketrans 提供了从 instr 到 outstr 的字节映射。当我们使用 translate 时,如果找到来自 instr 的任何字符,它将被替换为来自 outstr 的相应字符。
