如何将字符串转换为电话号码 [英] How to convert Strings to into a phone number

查看:205
本文介绍了如何将字符串转换为电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



编写一个将字符串作为参数的函数并返回电话号码
对应于该字符串作为结果。
电话号码也应该是一个字符串。
转换规则是电话号码规则的标准词汇:

lockquote
a,b或c地图到2

,'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。 b
$ b

 用于字符中的字符:
if char =='a'或者char =='b'或者char =='c':
print 2,

等等,但是当我调用函数 strng_to_num(apples)
输出是 2 7 7 5 3 7 我要' 277537' 。有反正去除空间吗?

解决方案



除了AttributeError:
导入字符串
translationdict = string.maketrans(abcdefghijklmnopqrstuvwxyz,22233344455566677778889999)

out_str = in_str.lower()。translate(translationdict)
return out_str

在这个问题的评论中,ooga提到的算法肯定是比较快的,但是需要比建立一个翻译字典更强烈的思想。这种方式适用于python2或者python3,但是这里是 maketrans 的相关文档.html#string.maketransrel =nofollow> Python2 Python3


I've been stuck on this questions for so long this is the question:

Write a function that takes a string as an argument and returns the phone number corresponding to that string as the result. The phone number should also be a string. The conversion rules are the standard word to phone number rules:

'a', 'b' or 'c' maps to 2

'd', 'e' or 'f' maps to 3

'g', 'h' or 'i' maps to 4

'j', 'k', or 'l' maps to 5

'm', 'n', or 'o' maps to 6

'p', 'q', 'r', or 's' maps to 7

't', 'u', or 'v' maps to 8

'w', 'x', 'y', or 'z' maps to 9.

Basically I tried

for char in word:
    if char == 'a' or char == 'b' or char == 'c':
    print 2,

and so on but when I call the function strng_to_num("apples") the output is 2 7 7 5 3 7 where I want '277537'. Is there anyway to remove the spaces?

解决方案

I'd do it like this:

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

The algorithm ooga alluded to in the comment to the question is definitely faster but requires a bit more intense thought than just building a translation dict. This way works for python2 or python3, but here are the relevant docs for maketrans in Python2 and Python3

这篇关于如何将字符串转换为电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆