在python中用数字替换单词中的多个字母?

btxsgosb  于 2023-01-24  发布在  Python
关注(0)|答案(3)|浏览(142)

似乎想不出如何用数字代替字母。
比方说

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

^我知道以上是错误的^
我应该写什么函数?

svgewumm

svgewumm1#

使用字符串中的maketrans:

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

输出:

27275

maketrans from string模块给出了从instr到outstr的字节Map。当我们使用translate时,如果发现任何来自instr的字符,它将被替换为来自outstr的相应字符。

uqjltbpv

uqjltbpv2#

看情况而定。既然你似乎在努力学习,我将避免高级使用这些库。一种方法是:

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
sgtfey8w

sgtfey8w3#

不如这样:

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

相关问题