📜  python urlencode - Python (1)

📅  最后修改于: 2023-12-03 15:19:02.019000             🧑  作者: Mango

Python urlencode

When it comes to sending HTTP requests, you might need to encode URL parameters in a certain way. Python's urlencode function comes in handy for this task. In this article, we'll discuss everything you need to know about urlencode in Python.

What is urlencode?

urlencode is a Python function that encodes a dictionary or sequence of key-value pairs into a URL-encoded string. This encoded string can then be appended to a URL as a set of parameters.

How to Use urlencode

Here's an example of using urlencode with a dictionary:

from urllib.parse import urlencode

params = {'name': 'John', 'age': 25}
encoded_params = urlencode(params)
print(encoded_params)

Output:

'age=25&name=John'

The urlencode function takes a dictionary as an argument and returns a URL-encoded string. In the example above, params is a dictionary with two key-value pairs. The urlencode function converts this dictionary into a string with the format key1=value1&key2=value2.

You can also use urlencode with a sequence of 2-tuples:

from urllib.parse import urlencode

params = [('name', 'John'), ('age', 25)]
encoded_params = urlencode(params)
print(encoded_params)

Output:

'age=25&name=John'

In this case, params is a list of tuples, with each tuple containing a key-value pair. The urlencode function converts this list into a string with the same format as before.

Encoding Spaces

When urlencode encounters spaces in the values of the dictionary or sequence, it will encode them as + by default. However, some servers may not recognize + as a space character. In these cases, you can use the quote function of the urllib.parse module to encode the spaces as %20 instead:

from urllib.parse import urlencode, quote

params = {'name': 'John Doe', 'age': 25}
encoded_params = urlencode({k: quote(v) for k, v in params.items()})
print(encoded_params)

Output:

'age=25&name=John%20Doe'

In this example, we use the quote function to percent-encode the space in the value of the name key. We then use a dictionary comprehension to apply this encoding to all values in the params dictionary.

Conclusion

urlencode is a useful function for encoding URL parameters in Python. It can take a dictionary or sequence of key-value pairs as input and return a URL-encoded string. Remember that if your values contain spaces, you may need to encode them as %20 instead of +.