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

Ran*_*ang 8 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
Run Code Online (Sandbox Code Playgroud)

roo*_*oot 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')
??????
Run Code Online (Sandbox Code Playgroud)

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

all(u'\u4e00' <= c <= u'\u9fff' for c in name.decode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

在你的python应用程序中,在内部使用unicode - 提前解码和编码延迟 - 创建一个unicode三明治.


Mar*_*ers 5

这在Python 2.7中对我来说很好,提供的name是一个unicode():

>>> ord(u'\u4e00') < 0x4e00
False
>>> ord(u'\u4dff') < 0x4e00
True
Run Code Online (Sandbox Code Playgroud)

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

>>> u'\u4e00' < u'\u4e00'
False
>>> u'\u4dff' < u'\u4e00'
True
Run Code Online (Sandbox Code Playgroud)

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

<form accept-charset="utf-8" action="...">
Run Code Online (Sandbox Code Playgroud)

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

name = self.request.get('name').decode('utf8')
Run Code Online (Sandbox Code Playgroud)