未命名

判断字符串是否是合法的ipv4地址

判断字符串是否是合法的 IPv4 地址,推荐使用 Python 标准库 ipaddress,简单且可靠。


import ipaddress
def is_valid_ipv4(ip: str) -> bool:
    try:
        ipaddress.IPv4Address(ip)
        return True
    except ValueError:
        return False

如果不想用标准库,也可以手写判断。规则是:

  • 必须由 4 段组成,用 . 分隔

  • 每段只能是数字

  • 每段范围 0 ~ 255

  • 不允许前导零,例如 01、001,但 0 本身可以


def is_valid_ipv4_manual(ip: str) -> bool:
    parts = ip.split(".")
    if len(parts) != 4:
        return False
    for part in parts:
        # 必须是非空、纯 ASCII 数字
        if not part or not all('0' <= c <= '9' for c in part):
            return False
        # 禁止前导零,如 01、001
        if len(part) > 1 and part[0] == '0':
            return False
        # 范围 0 ~ 255
        if int(part) > 255:
            return False
    return True

all 是 Python 的内置函数,用来判断一个可迭代对象里的所有元素是否都为真。

规则:

  • 如果 iterable 中所有元素都为真,返回 True

  • 只要有一个元素为假,返回 False

  • 如果 iterable 是空的,返回 True

all(c.isdigit() for c in part) 对空字符串会返回 True:

all([])                   # True,空的可迭代对象

isdigit() 会把一些非 ASCII 数字字符也判为 True,例如:


'1'.isdigit()   # True,全角数字
'²'.isdigit()    # True,上标数字
'一'.isdigit()   # False

这可能导致 IPv4 判断出现意外结果,比如:


part = '123'
all(c.isdigit() for c in part)  # True
int(part)                       # 123

未命名
https://mingsm17518.github.io/2026/09/30/刷题笔记/机考-虾皮信息/第3题/
作者
Ming
发布于
2026年9月30日
更新于
2026年10月2日
许可协议