Home  >  Q&A  >  body text

How to urlencode a query string in Python?

<p>I'm trying to urlencode the string before submitting it. </p> <pre class="brush:php;toolbar:false;">queryString = 'eventName=' evt.fields["eventName"] '&' 'eventDescription=' evt.fields["eventDescription"];< /pre> <p><br /></p>
P粉245489391P粉245489391423 days ago459

reply all(2)I'll reply

  • P粉270891688

    P粉2708916882023-08-24 11:41:36

    Python 2

    What you are looking for is urllib.quote_plus:

    safe_string = urllib.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')
    
    #Value: 'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24'

    Python 3

    In Python 3, the urllib package has been broken into smaller components. You would use urllib.parse.quote_plus< /code> (note the parse submodule)

    import urllib.parse
    safe_string = urllib.parse.quote_plus(...)

    reply
    0
  • P粉562845941

    P粉5628459412023-08-24 00:39:26

    You need to pass the parameters to urlencode()< /code> as a map (dict) or sequence of tuples, for example:

    >>> import urllib
    >>> f = { 'eventName' : 'myEvent', 'eventDescription' : 'cool event'}
    >>> urllib.urlencode(f)
    'eventName=myEvent&eventDescription=cool+event'

    Python 3 or higher

    Usingurllib.parse.urlencode< /代码>:

    >>> urllib.parse.urlencode(f)
    eventName=myEvent&eventDescription=cool+event

    Note that this does not perform url encoding in the usual sense (see the output). To do this, use urllib.parse.quote_plus.

    reply
    0
  • Cancelreply