Python: Importing urllib.quote

前端 未结 5 572
广开言路
广开言路 2021-01-30 00:22

I would like to use urllib.quote(). But python (python3) is not finding the module. Suppose, I have this line of code:

print(urllib.quote(\"châteu\"         


        
相关标签:
5条回答
  • 2021-01-30 00:56

    urllib went through some changes in Python3 and can now be imported from the parse submodule

    >>> from urllib.parse import quote  
    >>> quote('"')                      
    '%22'                               
    
    0 讨论(0)
  • 2021-01-30 00:59

    In Python 3.x, you need to import urllib.parse.quote:

    >>> import urllib.parse
    >>> urllib.parse.quote("châteu", safe='')
    'ch%C3%A2teu'
    

    According to Python 2.x urllib module documentation:

    NOTE

    The urllib module has been split into parts and renamed in Python 3 to urllib.request, urllib.parse, and urllib.error.

    0 讨论(0)
  • 2021-01-30 01:09

    Use six:

    from six.moves.urllib.parse import quote
    

    six will simplify compatibility problems between Python 2 and Python 3, such as different import paths.

    0 讨论(0)
  • 2021-01-30 01:10

    If you need to handle both Python 2.x and 3.x you can catch the exception and load the alternative.

    try:
        from urllib import quote  # Python 2.X
    except ImportError:
        from urllib.parse import quote  # Python 3+
    

    You could also use the python compatibility wrapper six to handle this.

    from six.moves.urllib.parse import quote
    
    0 讨论(0)
  • 2021-01-30 01:21

    This is how I handle this, without using exceptions.

    import sys
    if sys.version_info.major > 2:  # Python 3 or later
        from urllib.parse import quote
    else:  # Python 2
        from urllib import quote
    
    0 讨论(0)
提交回复
热议问题