Use urllib library

import urllib
finalurl = baseUrl + urllib.parse.quote(searchterm)

you can use quote_plus() to add + insted of %20 to undo this use

urllib.parse.unquote(str)

In Python 2, use urllib.quote() and urllib.unquote() respectively

Answer from Jaysheel Utekar on Stack Overflow
🌐
URL Encoder
urlencoder.io › python
How to encode URLs in Python | URLEncoder
That means, It doesn't encode / ... as well, then you can do so by supplying an empty string in the safe parameter like this- ... The quote() function encodes space characters to ....
Discussions

python - Convert spaces to in list - Stack Overflow
The urllib answer is, arguably, preferable because it makes your intent clearer: you are URL-encoding the string. Replacing spaces with is how you are doing it (assuming spaces are the only thing you need to worry about). More on stackoverflow.com
🌐 stackoverflow.com
My URL has spaces in it and Python won't let me make a request
You need to encode the file parameter to make the request. This is available in urlencode First delete &titles from your base string and then do something like this: from urllib.parse import urlencode title = urlencode({"titles": title}) You can actually pass all the parameters in urlencode: parameters = urlencode({"action": "query", "titles": title, "prop": "imageinfo", "iiprop": "url"}) or something to that effect. Then newQ = "https://en.wikipedia.org/w/api.php?" + parameters More on reddit.com
🌐 r/learnpython
3
2
December 2, 2020
Encode spaces in query parameter with %20 instead of +
Hi, I came across a web server today which wants percent encoding for spaces in the query parameter. Httpx encodes them with the ‘+’ sign which is not wrong at all. Now I am wondering what would be... More on github.com
🌐 github.com
2
3
qgis - Inserting instead of a space as a string - Geographic Information Systems Stack Exchange
If you are looking to URL encode your strings, try (for Python 2): ... This will handle spaces and a whole lot more. This post has a quick table of the different characters you need to encode. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. More on gis.stackexchange.com
🌐 gis.stackexchange.com
September 13, 2017
🌐
Python
docs.python.org › 3 › library › urllib.parse.html
urllib.parse — Parse URLs into components — Python 3.14.6 ...
By default, quote_plus() is used to quote the values, which means spaces are quoted as a '+' character and ‘/’ characters are encoded as /, which follows the standard for GET requests (application/x-www-form-urlencoded).
🌐
ProxiesAPI
proxiesapi.com › articles › url-encoding-and-decoding-in-python
URL Encoding and Decoding in Python | ProxiesAPI
February 6, 2024 - URL encoding/decoding in Python using urllib.parse. quote() encodes special characters like spaces as , while unquote() decodes them. Useful for building and parsing URLs.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-urlencode-a-querystring-in-python
How to Urlencode a Querystring in Python? - GeeksforGeeks
July 23, 2025 - ... 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.
🌐
Reddit
reddit.com › r/learnpython › my url has spaces in it and python won't let me make a request
r/learnpython on Reddit: My URL has spaces in it and Python won't let me make a request
December 2, 2020 -

I am scraping Wikipedia for information about retro video games. One of the things I want to grab from a page is the main image in the infobox. Here's the code for it. I am using

from urllib.request import urlopen
import json
import re

def getImage(href, name):
	default = 'n/a'
	query = 'https://en.wikipedia.org/w/api.php?action=query&prop=images&format=json&titles=' + href

	client = urlopen(query)
	data = json.loads(client.read())
	pids = data['query']['pages']
	pid = 0
	for page in pids:
		pid = page
	images = pids[pid]['images']

	# Search for the first image that matches the title or 'box art'
        # Use regular expressions for this
	for image in images:
		title = image['title'] #My Title has spaces and belongs in a URL!!!
		if (re.search('box art', title) != None) or (re.search(name, title) != None):
			newQ = 'https://en.wikipedia.org/w/api.php?action=query&titles=' + title + '&prop=imageinfo&iiprop=url' 
			client = urlopen(newQ) #This is where I'm getting the error
			data = json.loads(client.read())['query']['pages']
			pid = 0
			for page in data:
				pid = page
			img_url = data[pid]['imageinfo']['url']
                        return img_url
	return default

#Lets search for Super Smash Bros
href = 'Super_Smash_Bros._Melee'
name = 'Super Smash Bros. Melee'

#I expect this function to print the URL for the box art of SSBM 
print(getImage(href, name))

The file names of the images located through the Wikimedia API have spaces in them, and in order to find the URL of the box art, I have to make another query with the File name, but these files have spaces in them.

Go ahead and try the query yourself: https://en.wikipedia.org/w/api.php?action=query&titles=%27File:Super%20Smash%20Bros%20Melee%20box%20art.png%27&prop=imageinfo&iiprop=url

Since the query works in my browser, I do not believe my query is wrong. Here's the error python is giving me

PS C:\Users\Happy Customer\documents> python3 test.py
Traceback (most recent call last):
  File "test.py", line 70, in <module>
    print(getimg(link, name))
  File "test.py", line 57, in getimg
    client = urlopen(newQ)
  ##... unimportant nonsense....##
    raise InvalidURL(f"URL can't contain control characters. {url!r} "
http.client.InvalidURL: URL can't contain control characters. '/w/api.php?action=query&titles=File:Super Smash Bros Melee box art.png&prop=imageinfo&iiprop=url' (found at least ' ')

What am I to do if the file name has spaces in it and I need to make a Rest API call?!

🌐
SSOJet
ssojet.com › escaping › url-escaping-in-python
URL Escaping in Python | Escaping Techniques in Programming
The urllib.parse.quote() function from Python's standard library is your primary tool for this. It correctly replaces reserved characters with their percent-encoded equivalents, ensuring the URL remains valid and parsable. Consider encoding a filename or a query parameter value that might contain spaces or symbols.
Find elsewhere
🌐
iO Flood
ioflood.com › blog › python-url-encode
[SOLVED] Python URL Encode Using urllib.parse Functions
February 1, 2024 - Python has a built-in module urllib.parse that provides methods for manipulating URLs and their components, including a function for URL encoding: quote(). This function is a simple and effective tool for encoding URLs in Python. The quote() function takes a string (the URL) as an argument and returns a new string where all special characters have been replaced with their corresponding percent-encoded ASCII characters.
🌐
Delft Stack
delftstack.com › home › howto › python › python urlencode
How to Use Urlencode in Python | Delft Stack
February 15, 2024 - By applying urllib.parse.quote_plus(), we effectively replace special characters and spaces in the string with '+' signs. ... The output is delftstack$urllib, demonstrating the URL-encoded format of the input string.
🌐
ProxiesAPI
proxiesapi.com › articles › encoding-urls-in-python-with-urllib
Encoding URLs in Python with urllib | ProxiesAPI
We can encode the full URL, the path, and the query parameters separately using ... from urllib.parse import quote, quote_plus url = "https://www.example.com/path with spaces?query=foo bar" full_url = quote(url, safe='/') path = quote("/path with spaces") query = quote_plus("foo bar")
🌐
Devzery
devzery.com › post › urlencode-python-mastering-url-encoding-in-python
Python URL Encoding Made Simple: Learn urlencode, Query Strings & API Handling!
April 21, 2025 - Sometimes, you might need to encode ... query string. For example: ... from urllib.parse import quote path = '/user profile/images' encoded_path = quote(path) print(encoded_path) ... The quote function encodes each part of the path, ensuring that spaces and slashes are properly encoded. When working with non-ASCII ...
🌐
ProxiesAPI
proxiesapi.com › articles › properly-encode-urls-in-python-requests-with-urllib
Properly Encode URLs in Python Requests with urllib | ProxiesAPI
February 20, 2024 - For example, an unencoded space character would look like · my url when encoded. Encoding allows that URL to be transmitted properly. ... from urllib.parse import quote url = 'https://www.mywebsite.com/search?value=python tips' encoded_url = quote(url) print(encoded_url) # Prints: https://www.mywebsite.com/search?value=python tips
🌐
Temboo
temboo.com › python › url-encode
How to Encode a URL in Python
Spaces are replaced by either a plus sign (+) or with . You've probably seen URLs full of strange looking characters, and now you know why! The good news is that you don't actually have to worry about the specifics.
🌐
GitHub
gist.github.com › nkentaro › 37f25b802e825da7ab3b7f27c0303047
url encode and decode in python3 · GitHub
The quote() function encodes space to . Python also has a quote_plus() function that encodes space to plus sign (+). I've written about URL Encoding in python on my website.
🌐
GitHub
github.com › apache › arrow › issues › 34905
[Python] unexpected URL encoded path (white spaces) when uploading to S3 · Issue #34905 · apache/arrow
April 5, 2023 - OS: Windows/Linux Python: 3.10.10 ... s3fs.S3FileSystem), if the Path to the Parque File contains white spaces. White Spaces will be replaced by URL encoded Syntax e.g: A Directory Name like:...
Author   apache
🌐
PyTutorial
pytutorial.com › url-encoding-in-python-a-complete-guide
PyTutorial | URL Encoding in Python: A Complete Guide
January 28, 2026 - You can also specify a set of safe characters that should not be encoded. Let's look at a basic example. # Import the necessary module from urllib.parse import quote # A string with spaces and special characters original_string = "My Document & Report.pdf" # Encode the string encoded_string = quote(original_string) print(f"Encoded: {encoded_string}")