数据类型`NoneType`比较?

我正在尝试1-65535使用urlparse.

棘手的部分是,如果 URL 中没有端口号,urlparse(url).port则标识为NoneType

因此,我尝试根据数据类型进行简单的比较,但并没有像您在此示例中看到的那样真正起作用。

如果我NoneType用作数据类型,

elif type(u.port) == NoneType:

我收到错误

NameError: name 'NoneType' is not defined

我没有使用,validators因为它无法正确验证端口号。

TCP/UDP 端口号范围从 1-65535 开始。但是,validators无法识别端口1-9并且仍然接受大于65535.

代码

from urllib.parse import urlparse


def test(url):

    global u

    u = urlparse(url)

    print(' Port      : ', u.port)

    print(' Data Type : u.port %s\n'% type(u.port))


for url in ['example.com', 'example.com:1', 'http://example.com:1']:

    print(url)

    test(url)

    if type(u.port) == int:

        print(' Integer')

    elif type(u.port) == None:

        print(' None')

    # elif type(u.port) == NoneType:        # NameError: name 'NoneType' is not defined

    #   print(' None')

输出


example.com

 Port      :  None

 Data Type : u.port <class 'NoneType'>


example.com:1

 Port      :  None

 Data Type : u.port <class 'NoneType'>


http://example.com:1

 Port      :  1

 Data Type : u.port <class 'int'>


    Integer


LEATH
浏览 224回答 3
3回答

守候你守候我

不要比较要检查的类型,请None使用:elif u.port is None:&nbsp; &nbsp; print(' None')

尚方宝剑之说

您还可以通过以下方式检查 NoneType:elif isinstance(u.port, type(None)):&nbsp; &nbsp; print(' None')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python