user3463010
user3463010

Reputation: 41

Replacing multiple letters in a word with number in python?

Cant seem to figure out how to replace letters with numbers. for e.g.

lets say

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

The string I want to replace is again. The output i want to get is 27275. The outcome of these numbers should be in strings.

so far i have got:

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"

^I know the above is wrong^

What function should I write?

Upvotes: 1

Views: 4489

Answers (3)

venpa
venpa

Reputation: 4318

Use maketrans from string:

from string import maketrans
instr = "abcdenghi"
outstr = "222555777"
trans = maketrans(instr, outstr)
text = "again"
print text.translate(trans)

Output:

 27275

maketrans from string module gives byte mapping from instr to outstr. When we use translate, if any character from instr is found, it would be replaced with corresponding character from outstr.

Upvotes: 10

James Sapam
James Sapam

Reputation: 16940

How about:

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

Upvotes: 1

carlosdc
carlosdc

Reputation: 12142

It depends. Since it seems you're trying to learn, I'll avoid advanced uses of the libraries. One way would be the following:

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

Another way which is close to what you were trying to do in the code you showed in your question:

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

Upvotes: 2

Related Questions