比较python2.7中用户输入的unicode字符串

2024-09-30 08:25:38 发布

您现在位置:Python中文网/ 问答频道 /正文

将用户输入的字符串与另一个字符串进行比较的最佳方法是什么?在

例如:

# -*- coding: utf-8 -*-

from __future__ import unicode_literals

user_input = raw_input("Please, write árido: ").decode("utf8")
if u"árido" == user_input:
    print "OK"
else:
    print "FALSE"

编辑:

这个

^{pr2}$

印刷品:

type árbol: árbol
Encoding utf-8
User Input      Program Input
--------------------------------------------------
árbol          árbol   (raw value)
árbol          árbol   (unicode(value))
árbol          árbol   (value.decode('utf8'))
árbol          árbol   (normalize('NFC',value))


User Input              Program Input (Repr)
--------------------------------------------------
'\xc3\x83\xc2\xa1rbol'  u'\xe1rbol'
u'\xc3\xa1rbol'         u'\xe1rbol'     (unicode(value))
u'\xc3\xa1rbol'         u'\xe1rbol'     (value.decode('utf8'))
u'\xc3\xa1rbol'         u'\xe1rbol'     (normalize('NFC',value)))

有什么想法吗?我在使用其他语言(如Java)时没有问题。这只发生在python上。我用的是日蚀。在

提前感谢:)


Tags: 字符串inputrawvalueunicodeutf8utfdecode
2条回答

您当前的方法还不错,但您可能应该使用^{}进行比较。上面链接的文档解释了为什么这是个好主意。例如,尝试评估以下内容:

u'Ç' == u'Ç'

扰流板警报,这将给您False,因为左侧是序列U+0043(拉丁文大写字母C)U+0327(组合加符),右侧是单个字符U+00C7(拉丁文大写字母C加上加符)。在

您可以使用unicodedata.normalize()正确地处理这个问题,方法是首先将字符串转换为规范化的形式。例如:

^{pr2}$

你能检查一下终端的字符编码吗

import sys

sys.stdin.encoding

如果是UTF-8,那么解码就可以了。否则,您必须用正确的编码对原始输入进行解码。在

比如,raw_input()。解码(系统标准编码)如果需要,检查它是否与Unicode规范化一起正确。在

相关问题 更多 >

    热门问题