0

I am trying to encode and decode with utf-8. What is wierd is that I get an error trackback saying that I am using gbk.

oneword.decode("utf-8")]

below is the error trackback.

UnicodeEncodeError: 'gbk' codec can't encode character '\u2769' in position 1: illegal multibyte sequence

Can anyone tell me what to do? I seems that the decode parameter does not have effect.

Ray
2,51620 silver badges22 bronze badges
asked Jan 7, 2014 at 5:20
2
  • 3
    What is oneword? Please update your post with the result of print(oneword). Commented Jan 7, 2014 at 5:21
  • Actually repr(oneword) might be more useful. The UnidoceEncodeError makes it look like its trying to first encode oneword before decoding it, as if oneword is a bytes object. I haven't seen this behaviour before in Python 3 though. Commented Jan 7, 2014 at 7:25

1 Answer 1

1

I got it solved. Actually, I intended to output to a file instead of the console. In such situation, I have to explicitly indicate the decoding of the output target file. Instead of using open I used codecs.open.

import codecs
f = codecs.open(filename, mode='w', encoding='utf-8')

Thanks to @Bakuriu from the comments:

If you are using Python 3 you no longer need to import the codecs module. Just pass the encoding parameter to the built-in open function.

Henry Ecker
35.8k19 gold badges48 silver badges67 bronze badges
answered Jan 11, 2014 at 8:28
Sign up to request clarification or add additional context in comments.

2 Comments

In python3 there is no need to import the codecs module. Just pass the encoding parameter to the built-in open function. You can achieve the same behaviour in python2 using io.open.
Adding to @Bakuriu: The codecs module actually has several annoying bugs that will likely never be fixed, and performs worse than the io module components (open is io.open on Python 3); you basically never want to use codecs.open unless your code needs to run unmodified all the way back to Python 2.5 (as of 2.6, io.open exists).

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.