要删除非整数字符,请使用正则表达式方法。 [^0-9] 指定所有非 0-9 的字符,然后用空字符串替换。
import re
def decode(input):
output = re.sub('[^0-9]', '', input)
return output
列表理解可能更直观一些。我们本质上是构建一个只包含数字字符的数组,然后返回连接后的数组。
def decode(input):
output = [n for n in input if n.isnumeric()]
return ''.join(output)
因此,如果我们想通过测试用例,还需要做一些工作(即如果没有国家代码,则添加国家代码,并删除国家代码和实际电话号码之间的零)。
def get_phonenum(input):
# remove all non-numeric characters from the phone number
only_digits = decode(input)
# assuming that the inputs are constrained to country code 62
only_digits = only_digits if only_digits[:2] == '62' else '62' + only_digits
# remove zero between country code and actual phone number
phone_num = only_digits[:2] + only_digits[3:] if only_digits[2] == '0' else only_digits
return phone_num
跑步
test = ['+62 812-3456-7890',
'62081234567890',
'6281234567890',
'+6281234567890',
'081234567890',
'(62)81234567890',
'(62)081234567890',
'(+62)81234567890',
'(+62)081234567890']
for t in test:
print(get_phonenum(t))
输出
6281234567890
6281234567890
6281234567890
6281234567890
6281234567890
6281234567890
6281234567890
6281234567890
6281234567890