问题描述
这个话题已经在StackOverflow上了,但是我没有找到令人满意的解决方案:
我有一些来自服务器的Unicode字符串,并且我想匹配一些硬编码的字符串。
而且我知道为什么我不能只做一个==
但是我没有成功地正确转换它们(我不在乎我是否必须执行str-> unicode或unicode-> str)。
我尝试encode
和decode
,但未得到任何结果。
这是我收到的...
fromServer = {unicode} u'Führerschein n?tig'
fromCode = {str} 'Führerschein n?tig'
(如您所见,它是德语!)
在Python 2中如何让它们相等?
1楼
首先,请确保在文件顶部声明Python源文件的编码。 例如。 如果您的文件编码为latin-1:
# -*- coding: latin-1 -*-
其次,始终将文本存储为Unicode字符串:
fromCode = u'Führerschein n?tig'
如果从某处获取字节, str.decode
在处理文本之前使用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
。
2楼
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....