在Python中用数字替换单词中的多个字母?
我似乎搞不清楚怎么把字母换成数字。比如说,
假设
'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"
^我知道上面的代码是错的^
我应该写什么函数呢?
3 个回答
1
这样怎么样:
>>> 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'
>>>
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
10
使用字符串中的maketrans:
from string import maketrans
instr = "abcdenghi"
outstr = "222555777"
trans = maketrans(instr, outstr)
text = "again"
print text.translate(trans)
输出:
27275
字符串模块中的maketrans可以创建一个字节映射,从输入字符串(instr)到输出字符串(outstr)。当我们使用translate时,如果在输入字符串中找到了某个字符,它就会被替换成输出字符串中对应的字符。