Python 2:比较unicode和str

时间:2015-10-19 21:08:42

标签: python unicode encoding character-encoding python-2.x

这个主题已经在StackOverflow上,但我找不到任何令人满意的解决方案:

我有一些来自服务器的Unicode字符串,我在代码中有一些硬编码字符串,我想与之匹配。而且我确实理解为什么我不能成为==但是我没有成功地正确转换它们(我不在乎我是否要做str - > unicode或unicode - > str)。

我尝试了encodedecode,但它没有给出任何结果。

这是我收到的......

fromServer = {unicode} u'Führerschein nötig'
fromCode = {str} 'Führerschein nötig'

(你可以看到,它是德国人!)

如何在Python 2

中使它们等于

2 个答案:

答案 0 :(得分:2)

首先确保在文件顶部声明Python源文件的编码。例如。如果您的文件编码为latin-1:

# -*- coding: latin-1 -*-

第二,始终将文本存储为Unicode字符串:

fromCode = u'Führerschein nötig'

如果从某处获取字节,请在使用文本之前将其转换为带str.decode的Unicode。对于文本文件,请在打开文件时指定编码,例如:

# use codecs.open to open a text file
f = codecs.open('unicode.rst', encoding='utf-8')

将字节字符串与Unicode字符串进行比较的代码通常会随机失败,具体取决于系统设置或文本文件中使用的任何编码。不要依赖它,总是确保比较两个unicode字符串或两个字节字符串。

Python 3改变了这种行为,它不会尝试转换任何字符串。 'a'b'a'被视为不同类型的对象,并且比较它们将始终返回False

答案 1 :(得分:-1)

tested on 2.7

for German umlauts latin-1 is used.

if 'Führerschein nötig'.decode('latin-1') == u'Führerschein nötig':
    print('yes....')

yes....