如何将字符串转换为电话号码

Kir*_*rby 3 python string for-loop

我一直坚持这个问题很长时间这是个问题:

编写一个以字符串作为参数的函数,并返回与该字符串对应的电话号码作为结果.电话号码也应该是一个字符串.转换规则是电话号码规则的标准字:

'a','b'或'c'映射到2

'd','e'或'f'映射到3

'g','h'或'i'映射到4

'j','k'或'l'映射到5

'm','n'或'o'映射到6

'p','q','r'或's'映射到7

't','u'或'v'映射到8

'w','x','y'或'z'映射到9.

基本上我试过了

for char in word:
    if char == 'a' or char == 'b' or char == 'c':
    print 2,
Run Code Online (Sandbox Code Playgroud)

等等,但是当我调用该函数时strng_to_num("apples") ,输出就是2 7 7 5 3 7我想要的地方'277537'.无论如何要删除空格?

Ada*_*ith 11

我这样做:

def string_to_num(in_str):
    try:
        translationdict = str.maketrans("abcdefghijklmnopqrstuvwxyz","22233344455566677778889999")
    except AttributeError:
        import string
        translationdict = string.maketrans("abcdefghijklmnopqrstuvwxyz","22233344455566677778889999")

    out_str = in_str.lower().translate(translationdict)
    return out_str
Run Code Online (Sandbox Code Playgroud)

ooga在问题评论中提到的算法肯定更快,但需要比仅仅构建翻译词典更强烈的思考.这种方式适用于python2还是python3,但这里有相关的文档为maketransPython2Python3