I just can't understand how to translate such a string in Python 3

 u'Имя представителя' 

in cp1251.

In Python 2, this structure worked:

  u'Имя представителя'.encode('cp1251') 

Now I do everything the same way, but I get crocodiles. What to do ?

  • provide two complete code examples (with headers) that demonstrate the difference, because the results should be identical in both Python 2 and 3. Should you also explicitly describe your software environment (output to Windows console, to file, or somewhere else?) - jfs
  • Output to a csv-file that will be opened through exel ... - faoxis

2 answers 2

EDITED To output text to a file in the desired encoding, use the encoding parameter when opening a file for writing. No need to recode the text.

 with open('d:\\testfile.txt', mode='w', encoding='cp1251') as file: text = 'текст' file.write(text) 
     a = u'Имя представителя' print(a.encode('cp1251').decode('cp1251'))