How to unencode a string

MRAB python at
Fri Aug 28 00:05:03 CEST 2009

jakecjacobson wrote:
> This seems like a real simple newbie question but how can a person
> unencode a string?  In Perl I use something like: "$part=~ s/\%([A-Fa-
> f0-9]{2})/pack('C', hex($1))/seg;"
> If I have a string like Word1%20Word2%20Word3 I want to get Word1
> Word2 Word3.  Would also like to handle special characters like '",(){}
> [] etc/

The Python equivalent of your regular expression code is:

 >>> import re
 >>> s = "Word1%20Word2%20Word3"
 >>> re.sub(r"%([A-Fa-f0-9]{2})", lambda m: chr(int(, 16)), s)
'Word1 Word2 Word3'

The replacement is a lambda expression (an anonymous function), which is
called for each match with the match object and it works like this:

m                        # m is the match object               # get group 1 (the 2 hex digits)
int(, 16)      # convert to an integer
chr(int(, 16)) # convert to a character

More information about the Python-list mailing list