3

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?

SharpAffair
  • 5,558
  • 13
  • 78
  • 158
  • 1
    What have you tried so far? [`urllib.urlencode`](https://docs.python.org/2/library/urllib.html#urllib.urlencode)? – jonrsharpe Jun 15 '14 at 23:29
  • [Duplicate](http://stackoverflow.com/questions/875771/how-does-one-encode-and-decode-a-string-with-python-for-use-in-a-url)? – hd1 Jun 15 '14 at 23:34

2 Answers2

7

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
Fabricator
  • 12,722
  • 2
  • 27
  • 40
4

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'
CodeManX
  • 11,159
  • 5
  • 49
  • 70