You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现个性化车牌校验:数字不得位于中部仅可出现在末尾

个性化车牌合法性校验逻辑补全

现有规则梳理

当前代码已实现3项校验规则:

  • 车牌必须以至少2个字母开头
  • 车牌长度范围为2-6位,仅允许包含字母、数字
  • 车牌禁止出现句号、空格、各类标点符号

待补全规则实现思路

待实现规则为数字仅允许连续出现在车牌末尾,不得夹在字母中间,判断逻辑如下:

  • 遍历字符时用标记位记录是否已经遇到数字
  • 一旦进入数字段(即遇到第一个数字),后续所有字符必须为数字,若再出现字母直接判定非法
  • 补充常规号牌校验逻辑:数字段首位不能为0,如不需要该规则可直接删除对应判断行

TODO位置补全代码

将以下代码直接替换原代码中的TODO注释段即可:

num_started = False
for c in s:
    if c.isdigit():
        # 数字段首位为0判定非法,不需要可删除下面两行
        if not num_started and c == "0":
            return False
        num_started = True
    else:
        # 已出现数字后又碰到字母,说明数字位于车牌中部,非法
        if num_started:
            return False

补全后完整可运行代码

def main():
    plate = input("Plate: ")
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")


def is_valid(s):

# All vanity plates must start with at least two letters
    if s[0].isalpha() == False or s[1].isalpha() == False:
        return False

# vanity plates may contain a maximum of 6 characters (letters or numbers) and a minimum of 2 characters
    if len(s) < 2 or len(s) > 6:
        return False

# Numbers cannot be used in the middle of a plate; they must come at the end
    num_started = False
    for c in s:
        if c.isdigit():
            # 数字段首位为0判定非法,不需要可注释该判断
            if not num_started and c == "0":
                return False
            num_started = True
        else:
            if num_started:
                return False

# No periods, spaces, or punctuation marks are allowed
    for c in s:
        if c in [".", " ", ",", "!", "?"]:
            return False

# PASSES ALL TESTS
    return True


main()

内容的提问来源于stack exchange,提问作者Curious Cat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 09:54:24