5

When I try to convert unicode:

a = u"Тест"

To string:

str(a)

I got this error:

'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

I need str(a) to give me output:

>> str(a)
>> 'Тест'
UnLiMiTeD
  • 1,000
  • 1
  • 9
  • 17
  • Check out this link: http://stackoverflow.com/questions/2365411/python-convert-unicode-to-ascii-without-errors –  Apr 25 '13 at 15:03
  • I have been watching this tag for a few weeks now and I see this question almost every day. Did you even try searching for this error before you posted? Here, [over 500 results](http://stackoverflow.com/search?q=%22%27ascii%27+codec+can%27t+encode%22). – R. Martinho Fernandes Apr 25 '13 at 15:05
  • Yes I did and no one does not handle my case. – UnLiMiTeD Apr 25 '13 at 15:07
  • @UnLiMiTeD Perhaps you should explain why the other answers don't apply. Otherwise you will end up getting the same answers that people provided in the other questions. Until you do so, I will assume this question is not different from any of the other hundreds like it and am voting to close it. – R. Martinho Fernandes Apr 25 '13 at 15:09
  • Also useful http://nedbatchelder.com/text/unipain.html – R. Martinho Fernandes Apr 25 '13 at 15:17

1 Answers1

4

Pick an encoding that can encode Cyrillic symbols, such as UTF-8:

>>> a = u'Тест'

>>> a.encode('utf-8')
'\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82'

The ASCII table doesn't have code points for Cyrillic characters, so you need to specify an encoding explicitly.

But if all you want is just print the string, then what you should care about is the encoding of your terminal and the system font.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • I got this, but I need to show them in the string encoded like string 'Test'. – UnLiMiTeD Apr 25 '13 at 15:23
  • 1
    @UnLiMiTeD A search for "python transliterate cyrillic" gives [this](http://stackoverflow.com/a/14173535/1258041) among other stuff, if that is what you need. – Lev Levitsky Apr 25 '13 at 15:26