2017-04-24 36 views
1

我在Python 2.7中國的計劃,是給我一些問題問題與中國在python

代碼:

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

我得到的錯誤:

test_chinese.py:6: UnicodeWarning:Unicode等於比較無法將兩個參數轉換爲Unicode - 將它們解釋爲不相等 if(command == u「 」.encode('utf-8')):

有什麼不對嗎?

+0

嘗試下面的代碼if(command == u「你好」):'而不是'if(command == u「你好」.encode ('utf-8')):' – Minji

回答

1

你不需要encode您的Unicode文本:u"你好",所以只需使用:

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

老實說,你應該只使用Python 3對Unicode的支持要好得多。的確,str現在是unicode點的序列,與Python 2中的「字節串」不同,後者已更改爲bytes數據類型。在Python 3中,所有你需要做的是:

command = input(">>> ") 
if command == "你好": 
    print("etc") 
+0

也許你應該給出有效的一個原因,爲什麼你鼓勵OP在這種情況下使用python2 – repzero

+1

@repzero抱歉,什麼?我鼓勵他們使用* Python 3 *,主要是爲了更簡化的unicode支持。 –

+0

把這個放在你的迴應中!不要在沒有備份的情況下提出建議! – repzero