Escaping Text for URLs in Python

TheJoeCoder

programmingpython

69 Words … ⏲ Reading Time:18 Seconds

2024-11-28 08:58 +0000


Escaping text for is really easy in Python. In fact, I used it for this project. Here’s how to do it:

from urllib.parse import quote

starting_text = "Test!"
escaped_text = quote(starting_text)

Initially, I thought that urllib.parse.urlencode should be used for this but I didn’t read the documentation properly. I realised that urllib.parse.urlencode is used for creating query strings from a dict, whereas urllib.parse.quote is actually used for escaping text.