1

I have a Chinese program in python 2.7 that is giving me some problems

Code:

# -*- coding: gb2312 -*- 
import sys
command = raw_input(">>> ").decode(sys.stdin.encoding)
if (command == u"你好".encode('utf-8')):
    print "etc"

I get the error:

test_chinese.py:6: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal if (command == u"����".encode('utf-8')):

Is there anything incorrect?

1
  • try this code if (command == u"你好"): instead of if (command == u"你好".encode('utf-8')): Commented Apr 24, 2017 at 1:14

1 Answer 1

1

You don't need to encode your unicode literal: u"你好", so just use:

import sys
command = raw_input(">>> ").decode(sys.stdin.encoding)
if command == u"你好":
    print "etc"

Honestly, you should just use Python 3. Support for unicode is much better. Indeed, str are now sequences of unicode points, unlike "byte strings" in Python 2, which have been changed to the bytes data type. In Python 3, all you would need to do is:

command = input(">>> ")
if command == "你好":
    print("etc")
Sign up to request clarification or add additional context in comments.

3 Comments

maybe you should gave valid ONE reason why you are encouraging the OP to use python2 in this case
@repzero sorry, what? I'm encouraging them to use Python 3, mostly for it's more streamlined unicode support.
Well put that in your response! don't go making a suggestion without backing it up!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.