How to URLEncode a Query String in Python

We can make use of the urlencode function from urllib.parse module to do a URL encoding.

Let's take a few examples.

Example 1

    from urllib.parse import urlencode
    product_query_params = {
        'product': 'Smart Phone',
        'name': "iPhone 15",
        'model': 15
    product_url_encoded_query = urlencode(product_query_params)
    print("URL-encoded Query String:", product_url_encoded_query)

    URL-encoded Query String: product=Smart+Phone&name=iPhone+15&model=15

Example 2:

    from urllib.parse import urlencode
    movie_details_query_data = {
        'title': 'Inception',
        'year': 2010,
        'director': 'Christopher Nolan',
        'genre': 'Science Fiction',
        'rating': 8.8,
    url_encoded_movie_details = urlencode(movie_details_query_data)

    URL-encoded Query String: title=Inception&year=2010&director=Christopher+Nolan&genre=Science+Fiction&rating=8.8

URLEncode a Query String in Python

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap