In [1]:
import urllib.parse

In [2]:
s = '日本語'

In [3]:
s_quote = urllib.parse.quote(s)

In [4]:
print(s_quote)


%E6%97%A5%E6%9C%AC%E8%AA%9E

In [5]:
print(type(s_quote))


<class 'str'>

In [6]:
b = s.encode()

In [7]:
print(b)


b'\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e'

In [8]:
print(type(b))


<class 'bytes'>

In [9]:
print(urllib.parse.quote(b))


%E6%97%A5%E6%9C%AC%E8%AA%9E

In [10]:
s_quote_sj = urllib.parse.quote(s, encoding='shift-jis')

In [11]:
print(s_quote_sj)


%93%FA%96%7B%8C%EA

In [12]:
b_sj_quote = urllib.parse.quote(s.encode('shift-jis'))

In [13]:
print(b_sj_quote)


%93%FA%96%7B%8C%EA

In [14]:
print(s_quote_sj == b_sj_quote)


True

In [15]:
print(urllib.parse.quote('http://x-y_z.com'))


http%3A//x-y_z.com

In [16]:
print(urllib.parse.quote('http://x-y_z.com', safe=''))


http%3A%2F%2Fx-y_z.com

In [17]:
print(urllib.parse.quote('http://x-y_z.com', safe='/:'))


http://x-y_z.com

In [18]:
print(urllib.parse.quote('+ /'))


%2B%20/

In [19]:
print(urllib.parse.quote_plus('+ /'))


%2B+%2F

In [20]:
print(urllib.parse.quote_plus('+ /', safe='+/'))


++/

In [21]:
page_title = '日本語'

In [22]:
base_ja = 'https://ja.wikipedia.org/wiki/'

In [23]:
print(base_ja + urllib.parse.quote(page_title))


https://ja.wikipedia.org/wiki/%E6%97%A5%E6%9C%AC%E8%AA%9E

In [24]:
full_url = 'https://ja.wikipedia.org/wiki/日本語'

In [25]:
print(urllib.parse.quote(full_url, safe=':/'))


https://ja.wikipedia.org/wiki/%E6%97%A5%E6%9C%AC%E8%AA%9E

In [26]:
print(base_ja + urllib.parse.quote('OK コンピューター'))


https://ja.wikipedia.org/wiki/OK%20%E3%82%B3%E3%83%B3%E3%83%94%E3%83%A5%E3%83%BC%E3%82%BF%E3%83%BC

In [27]:
print(base_ja + urllib.parse.quote('OK コンピューター'.replace(' ', '_')))


https://ja.wikipedia.org/wiki/OK_%E3%82%B3%E3%83%B3%E3%83%94%E3%83%A5%E3%83%BC%E3%82%BF%E3%83%BC

In [28]:
print(s_quote)


%E6%97%A5%E6%9C%AC%E8%AA%9E

In [29]:
print(urllib.parse.unquote(s_quote))


日本語

In [30]:
print(s_quote_sj)


%93%FA%96%7B%8C%EA

In [31]:
print(urllib.parse.unquote(s_quote_sj))


���{��

In [32]:
print(urllib.parse.unquote(s_quote_sj, 'shift-jis'))


日本語

In [33]:
print(urllib.parse.unquote('a+b'))


a+b

In [34]:
print(urllib.parse.unquote_plus('a+b'))


a b

In [35]:
b_unquote = urllib.parse.unquote_to_bytes(s_quote)

In [36]:
print(b_unquote)


b'\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e'

In [37]:
print(b_unquote.decode())


日本語

In [38]:
b_unquote_sj = urllib.parse.unquote_to_bytes(s_quote_sj)

In [39]:
print(b_unquote_sj)


b'\x93\xfa\x96{\x8c\xea'

In [40]:
print(b_unquote_sj.decode('shift-jis'))


日本語