20

I've got a string from an HTTP header, but it's been escaped.. what function can I use to unescape it?

myemail%40gmail.com -> [email protected]

Would urllib.unquote() be the way to go?

asked Apr 23, 2009 at 4:36

4 Answers 4

38

I am pretty sure that urllib's unquote is the common way of doing this.

>>> import urllib
>>> urllib.unquote("myemail%40gmail.com")
'[email protected]'

There's also unquote_plus:

Like unquote(), but also replaces plus signs by spaces, as required for unquoting HTML form values.

answered Apr 23, 2009 at 4:41
Sign up to request clarification or add additional context in comments.

1 Comment

K, just wanted to make sure.. I hate using a function that appears to do the job, but ends up only working with a few examples that I did and breaking with real world vars. heh. Then it becomes impossible to track down the problem.. :P
4

In Python 3, these functions are urllib.parse.unquote and urllib.parse.unquote_plus.

The latter is used for example for query strings in the HTTP URLs, where the space characters () are traditionally encoded as plus character (+), and the + is percent-encoded to %2B.

In addition to these there is the unquote_to_bytes that converts the given encoded string to bytes, which can be used when the encoding is not known or the encoded data is binary data. However there is no unquote_plus_to_bytes, if you need it, you can do:

def unquote_plus_to_bytes(s):
 if isinstance(s, bytes):
 s = s.replace(b'+', b' ')
 else:
 s = s.replace('+', ' ')
 return unquote_to_bytes(s)

More information on whether to use unquote or unquote_plus is available at URL encoding the space character: + or %20.

answered Feb 10, 2015 at 15:09

Comments

2

Yes, it appears that urllib.unquote() accomplishes that task. (I tested it against your example on codepad.)

answered Apr 23, 2009 at 4:42

Comments

0

Small correction to the previous answers (tested with python 3.11) -

from urllib.parse import unquote
unquote('myemail%40gmail.com')
'[email protected]'
answered Jun 8, 2024 at 16:07

1 Comment

Most of the answers are 15 years old. The update you provide was already mentioned in an answer from 10 years ago.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.