Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Urlencode cyrillic characters in Python

I need to convert a cyrillic string to its urlencoded version in Windows-1251 encoding. For the following example string:

Моцарт

The correct result should be:

%CC%EE%F6%E0%F0%F2

In PHP, I would simply do the following:

$request = urlencode(iconv("UTF-8", "windows-1251", "Моцарт"));
echo $request;

How to accomplish the same goal in Python?

like image 313
SharpAffair Avatar asked Mar 20 '26 08:03

SharpAffair


2 Answers

Use the decode and encode method on string, then use urllib.quote

import urllib
print urllib.quote(s.decode('utf8').encode('cp1251'))

prints

%CC%EE%F6%E0%F0%F2
like image 130
Fabricator Avatar answered Mar 22 '26 20:03

Fabricator


In Python 3, use the quote() function found in urllib.request:

from urllib import request

request.quote("Моцарт".encode('cp1251'))

# '%CC%EE%F6%E0%F0%F2'
like image 26
CodeManX Avatar answered Mar 22 '26 22:03

CodeManX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!