验证邮政编码?

新手上路,请多包涵

我在网上做一些教程……我被困在一个练习中:定义一个函数 postalValidate(S) 首先检查 S 是否代表有效的邮政编码。 注意: 我应该用字符串、列表、if 语句、循环和其他基本结构(如变量和函数)来解决它。

首先,删除所有空格;余数必须是 L#L#L# 的形式,其中 L 是字母(小写或大写), # 是数字。

如果 S 不是有效的邮政编码,则返回布尔值 False 。如果 S 有效,则以 nice 格式返回相同邮政编码的版本 L#L#L# 其中每个 L 是大写。

我已经为这些练习创建了一个代码,但评分者说这是错误的,但我也会发布它。

 def postalValidate(S):
   while " " in S:
     S.remove(" ")
   for i in range(1,6,2):
     S.isdigit(S[i])
   for j in range(0,5,2):
     S.upper(S[j]
     S.isalpha(S[j])
   return True

原文由 Reginald 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 850
2 个回答

这显然是正则表达式的工作,虽然我不知道你是否应该在练习中使用它们……

我将此作为答案发布,以防万一。否则,请告诉我们…

 #/usr/bin/evn python

import re
zipCode = re.compile(r"\s*(\w\d\s*){3}\s*")

if __name__ == "__main__":
    samples = [
        "           44F 4 F", #Invalid
        "  L0L0L0    ", #Valid
        "  L0  L0  L0    ", #Valid
    ]

    for sample in samples:
        if zipCode.match(sample):
            print "The string %s is a valid zipCode (nice and clean: %s)" % (sample, sample.replace(" ", "").upper())
        else:
            print "The string %s is NOT a valid zipCode" % sample


编辑:

由于你不能使用正则表达式,我建议你改变思维方式……而不是检查字符是否属于有效的邮政编码,我建议你做相反的事情:检查它们是否不属于在有效的邮政编码中,一旦检测到放错(或错误)的字符就返回 False:

 def postalValidate(S):
    S = S.upper().replace(" ", "")
    if len(S) == 6:
        for i in range(len(S)):
            if i % 2 == 0:
                #Even index (0, 2, 4, 6...) , has to be 'letter'
                if not(S[i].isalpha()):
                    return False
            else:
                #Odd index (1, 3, 5, 7...), must be 'number'
                if not(S[i].isdigit()):
                    return False

    else:
        #You can save some cpu ticks here... at this point, the string has to be of length 6 or you know it's not a zip
        return False
    return S

return 语句停止当前函数的执行,所以一旦您意识到要检查的字符串有“错误”,您就可以返回 False(一旦您知道它无效就没有继续检查的意义了,对吧?)

原文由 BorrajaX 发布,翻译遵循 CC BY-SA 3.0 许可协议

我碰巧正在研究同一个教程,具有相同的编码约束。经过几个小时的挠头:

 def postalValidate(S):
   S = S.replace(" ","")
   if len(S) != 6 or S.isalpha() or S.isdigit():
      return False
   if not S[0:5:2].isalpha():
      return False
   if not S[1:6:2].isdigit():
      return False
   return S.upper()

原文由 timothykc 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题