用户可以使用以下任何格式输入电话号码:
07xxxxxxxxx
00447xxxxxxxxx
447xxxxxxxxx
+447xxxxxxxxx
我需要帮助创建一个函数,该函数将采用上述任何格式的数字并将其作为国际格式+447xxxxxxxxx
返回。
这是我到目前为止所拥有的
def _clean_mobile(mobile):
import re
if re.match('^+44', mobile):
return mobile
elif re.match('^44', mobile):
return "+" + mobile
答案 0 :(得分:2)
import re
FORMATS = ['^07', '^00447', '^447', '^\+447']
def sanitize(mobile):
mobile = re.sub('\s+', '', mobile) # strip whitespaces
for format in FORMATS:
if re.match(format, mobile):
return re.sub(format + '(\d{9})', '+447\g<1>', mobile)
return mobile
sanitize('00447123456789') # +447123456789
sanitize('07123456789') # +447123456789
sanitize('447123456789') # +447123456789
sanitize('+44 712 345 67 89')# +447123456789
答案 1 :(得分:2)
def standardizePhoneNumber(mobile):
import re
valid_prefixes = '[+447|447|00447|07]'
result = re.match('^' + valid_prefixes + '*([0-9]{9})$', mobile)
if result:
return '+447' + result.group(1)
else:
return None # invalid format
print standardizePhoneNumber('07111111111')
print standardizePhoneNumber('00447111111111')
print standardizePhoneNumber('447111111111')
print standardizePhoneNumber('+447111111111')
print standardizePhoneNumber('456789456')
答案 2 :(得分:1)
这是使用Python format
方法的可能简单的解决方案:
numbers= ['07345216342', '00447345216342', '447345216342', '+447345216342'] #input
for i in numbers:
print '+447{0:0=9d}'.format(int(str(i)[-9:]))
输出:
+447345216342
+447345216342
+447345216342
+447345216342