Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • webscraping
  • Beautiful Soup
  • Selenium
  • Scrapy
  • urllib
  • open cv
  • Data analysis
  • Machine learning
  • NLP
  • Deep learning
  • Data Science
  • Interview question
  • ML math
  • ML Projects
  • ML interview
  • DL interview
Open In App
Next Article:
How to Convert Bytes to String in Python ?
Next article icon

How to Urlencode a Querystring in Python?

Last Updated : 07 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

URL encoding a query string consists of converting characters into a format that can be safely transmitted over the internet. This process replaces special characters with a '%' followed by their hexadecimal equivalent. In this article, we will explore three different approaches to urlencode a querystring in Python.

What is Urlencode in Python?

The urlencode is a function often used in web development and networking to encode a set of data into a format suitable for inclusion in a URL query string. This encoding ensures that special characters within the data do not interfere with the structure of the URL. For example, spaces are replaced with %20 or +, and special characters like &, =, ?, etc., are converted to their corresponding percent-encoded representations.

URLencode a Querystring in Python

Below are the possible approaches to urlencode a querystring in Python.

  • Using urllib.parse.urlencode
  • Using requests library
  • Using urllib.parse.quote_plus for Custom Encoding

URLencode a Querystring Using urllib.parse.urlencode

In this example, we are using urllib.parse.urlencode from the urllib.parse module to URL-encode a dictionary. This method handles encoding spaces as plus signs and ensures the parameters are properly formatted.

Python
import urllib.parse data = {     "site": "GeeksforGeeks",     "topic": "Python URL encoding",     "level": "Intermediate" } encoded_data = urllib.parse.urlencode(data) print(encoded_data) 

Output
site=GeeksforGeeks&topic=Python+URL+encoding&level=Intermediate 

URLencode a Querystring Using requests library

In this example, we are using the requests library's internal method _encode_params to URL-encode a dictionary. This method provides a convenient way to handle encoding when working with HTTP requests.

Python
import requests data = {     "site": "GeeksforGeeks",     "topic": "Python URL encoding",     "level": "Intermediate" } encoded_data = requests.models.RequestEncodingMixin._encode_params(data) print(encoded_data) 

Output:

site=GeeksforGeeks&topic=Python+URL+encoding&level=Intermediate

URLencode a Querystring Using urllib.parse.quote_plus for Custom Encoding

In this example, we are manually encoding each key-value pair using urllib.parse.quote_plus for more granular control over the URL-encoding process. This method allows customization of how each part of the query string is encoded.

Python
import urllib.parse data = {     "site": "GeeksforGeeks",     "topic": "Python URL encoding",     "level": "Intermediate" } encoded_data = '&'.join([f"{urllib.parse.quote_plus(key)}={urllib.parse.quote_plus(value)}" for key, value in data.items()]) print(encoded_data) 

Output
site=GeeksforGeeks&topic=Python+URL+encoding&level=Intermediate 



Next Article
How to Convert Bytes to String in Python ?

A

anjalibo6rb0
Improve
Article Tags :
  • Python
  • Python-requests
Practice Tags :
  • python

Similar Reads

  • Convert Unicode String to a Byte String in Python
    Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular
    2 min read
  • Check for URL in a String - Python
    We are given a string that may contain one or more URLs and our task is to extract them efficiently. This is useful for web scraping, text processing, and data validation. For example: Input: s = "My Profile: https://auth.geeksforgeeks.org/user/Prajjwal%20/articles in the portal of https://www.geeks
    4 min read
  • Convert a String to Utf-8 in Python
    Unicode Transformation Format 8 (UTF-8) is a widely used character encoding that represents each character in a string using variable-length byte sequences. In Python, converting a string to UTF-8 is a common task, and there are several simple methods to achieve this. In this article, we will explor
    3 min read
  • How to Convert Bytes to String in Python ?
    We are given data in bytes format and our task is to convert it into a readable string. This is common when dealing with files, network responses, or binary data. For example, if the input is b'hello', the output will be 'hello'. This article covers different ways to convert bytes into strings in Py
    2 min read
  • Requesting a URL from a local File in Python
    Making requests over the internet is a common operation performed by most automated web applications. Whether a web scraper or a visitor tracker, such operations are performed by any program that makes requests over the internet. In this article, you will learn how to request a URL from a local File
    4 min read
  • Convert Hex to String in Python
    Hexadecimal (base-16) is a compact way of representing binary data using digits 0-9 and letters A-F. It's commonly used in encoding, networking, cryptography and low-level programming. In Python, converting hex to string is straightforward and useful for processing encoded data. Using List Comprehen
    2 min read
  • How To Print Unicode Character In Python?
    Unicode characters play a crucial role in handling diverse text and symbols in Python programming. This article will guide you through the process of printing Unicode characters in Python, showcasing five simple and effective methods to enhance your ability to work with a wide range of characters Pr
    2 min read
  • Convert binary to string using Python
    We are given a binary string and need to convert it into a readable text string. The goal is to interpret the binary data, where each group of 8 bits represents a character and decode it into its corresponding text. For example, the binary string '01100111011001010110010101101011' converts to 'geek'
    3 min read
  • How To Convert Unicode To Integers In Python
    Unicode is a standardized character encoding that assigns a unique number to each character in most of the world's writing systems. In Python, working with Unicode is common, and you may encounter situations where you need to convert Unicode characters to integers. This article will explore five dif
    2 min read
  • Node.js querystring.unescape() Method
    On the specified str, the querystring.unescape() method decodes URL percent-encoded characters. This method converts a percent-encoding string into a normal string. It means it decodes any percent-encoding string into a normal string by removing the % symbol. This method iterates through the string
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences