似乎无法弄清楚如何用数字替换字母。例如。
让我们说
'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"
^我知道上面的错误^
我应该写什么功能?
答案 0 :(得分:10)
使用来自字符串的maketrans:
from string import maketrans
instr = "abcdenghi"
outstr = "222555777"
trans = maketrans(instr, outstr)
text = "again"
print text.translate(trans)
输出:
27275
来自字符串模块的maketrans提供从instr到outtr的字节映射。当我们使用translate时,如果找到instr中的任何字符,它将被替换为来自outstr的相应字符。
答案 1 :(得分:2)
这取决于。由于您似乎正在尝试学习,我将避免使用这些库的高级用法。一种方法是:
def lett_to_num(word):
replacements = [('a','2'),('b','2'),('d','5'),('e','5'),('n','5'),('g','7'),('h','7'),('i','7')]
for (a,b) in replacements:
word = word.replace(a,b)
return word
print lett_to_num('again')
另一种方法与您在问题中显示的代码中所做的很接近:
def lett_to_num(word):
out = ''
for ch in word:
if ch=='a' or ch=='b' or ch=='d':
out = out + '2'
elif ch=='d' or ch=='e' or ch=='n':
out = out + '5'
elif ch=='g' or ch=='h' or ch=='i':
out = out + '7'
else:
out = out + ch
return out
答案 2 :(得分:0)
怎么样:
>>> d = {'a': 2, 'c': 2, 'b': 2,
'e': 5, 'd': 5, 'g': 7,
'i': 7, 'h': 7, 'n': 5}
>>> ''.join(map(str, [d[x] if x in d.keys() else x for x in 'again']))
'27275'
>>>
>>> ''.join(map(str, [d[x] if x in d.keys() else x for x in 'againpp']))
'27275pp'
>>>