Python 2.7:测试字符串中的字符是否都是中文字符

时间:2013-05-08 13:10:32

标签: python python-2.7

以下代码测试字符串中的字符是否都是中文字符。它适用于Python 3,但不适用于Python 2.7。我如何在Python 2.7中完成它?

for ch in name:
    if ord(ch) < 0x4e00 or ord(ch) > 0x9fff:
        return False

2 个答案:

答案 0 :(得分:12)

#  byte str (you probably get from GAE)
In [1]: s = """Chinese (汉语/漢語 Hànyǔ or 中文 Zhōngwén) is a group of related
        language varieties, several of which are not mutually intelligible,"""

#  unicode str
In [2]: us = u"""Chinese (汉语/漢語 Hànyǔ or 中文 Zhōngwén) is a group of related
        language varieties, several of which are not mutually intelligible,"""

#  convert to unicode using str.decode('utf-8')    
In [3]: print ''.join(c for c in s.decode('utf-8') 
                   if u'\u4e00' <= c <= u'\u9fff')
汉语漢語中文

In [4]: print ''.join(c for c in us if u'\u4e00' <= c <= u'\u9fff')
汉语漢語中文

为了确保所有角色都是中文,这样的事情应该是:

all(u'\u4e00' <= c <= u'\u9fff' for c in name.decode('utf-8'))

在你的python应用程序中,在内部使用unicode - 早期解码&amp;编码延迟 - 创建unicode sandwich

答案 1 :(得分:5)

这在Python 2.7中适用于我,提供的nameunicode()

>>> ord(u'\u4e00') < 0x4e00
False
>>> ord(u'\u4dff') < 0x4e00
True

如果直接将字符与unicode值进行比较,则不必在此使用ord

>>> u'\u4e00' < u'\u4e00'
False
>>> u'\u4dff' < u'\u4e00'
True

传入请求中的数据尚未解码为unicode,您需要先执行此操作。在表单标记上明确设置accept-charset属性,以确保浏览器使用正确的编码:

<form accept-charset="utf-8" action="...">

然后解码服务器端的数据:

name = self.request.get('name').decode('utf8')
相关问题