2014-03-26 68 views
1

不能想出如何用数字替换字母。例如,用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" 

^我知道上面是错误的^

我应该写什么功能?从串

+1

你认为你应该写什么函数?显示一点点努力,然后我们会更可能帮助你 – hd1

+0

为什么'n'是'5'? – jfs

+0

这只是一个例子。所以我可以再拼出'再'一词。 – user3463010

回答

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时,如果找到instr中的任何字符,它将被来自outstr的对应字符替换。

+0

也许在python3.x中提到这是一个字符串方法'str.maketrans'。 – msvalkon

+0

它适用于python 2.7 ...我已经在python 2.7中测试过。 – user3

+0

不,在python 2.7中,你将不得不'从字符串导入maketrans',因为在python 3.x中,任何字符串都有'maketrans'方法:''一个字符串“.maketrans()'。 – msvalkon

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 
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' 
>>>