Transform URL string into normal string in python

2020-02-09 06:10发布

Is there any way in python to transfrom this-> %CE%B1%CE%BB%20 into this: "αλ " which is its real representation?

Thanks in advance!

标签: python string
3条回答
男人必须洒脱
2楼-- · 2020-02-09 06:29

There are two encodings in play here. Your string has first been encoded as UTF-8, then each byte has been percent-encoded.

To get the original string back you need to first unquote it, and then decode it:

>>> import urllib
>>> s = '%CE%B1%CE%BB%20'
>>> result = urllib.unquote(s).decode('utf8')
>>> print result
αλ 

Note that you need a Unicode enabled console in order to display the value (if you get an error with the print statement, try running it in IDLE).

查看更多
闹够了就滚
3楼-- · 2020-02-09 06:29

python 3 answer

import urllib 
urllib.parse.unquote('/El%20Ni%C3%B1o/')

'/El Niño/'

source

查看更多
Emotional °昔
4楼-- · 2020-02-09 06:46

For python 2:

>>> import urllib2
>>> print urllib2.unquote("%CE%B1%CE%BB%20")
αλ 

For python 3:

>>> from urllib.parse import unquote
>>> print(unquote("%CE%B1%CE%BB%20"))
αλ

And here's code that works in all versions:

try:
    from urllib import unquote
except ImportError:
    from urllib.parse import unquote

print(unquote("%CE%B1%CE%BB%20"))
查看更多
登录 后发表回答