为什么 "ǃ".isalpha() 是 True 而 "!".isalpha() 是 False?

问题描述

我刚刚在解析来自 IANA 的数据时发现了这种奇怪的行为。

"ǃ".isalpha() # returns True
"!".isalpha() # returns False

显然,这两个感叹号是不同的:

In [62]: hex(ord("ǃ"))                                                          
Out[62]: '0x1c3'

In [63]: hex(ord("!"))                                                          
Out[63]: '0x21'

只是想知道有没有办法防止这种情况发生?这种行为的根源是什么?

解决方法

检查 Unicode Database 中的字符。 类似感叹号的 ǃ (\u1c3) 是一个字母:

import unicodedata
for c in "!ǃ":
    print(c,'{:04x}'.format(ord(c)),unicodedata.category(c),unicodedata.name(c))
! 0021 Po EXCLAMATION MARK
ǃ 01c3 Lo LATIN LETTER RETROFLEX CLICK
,

来自文档:

str.isalpha()

如果字符串中的所有字符都是 字母并且至少有一个字符,否则为 False。 字母字符是 Unicode 中定义的字符 字库为“字母”,即一般类别的字库 属性是“Lm”、“Lt”、“Lu”、“Ll”或“Lo”之一。请注意,这 不同于 Unicode 中定义的“Alphabetic”属性 标准。

这意味着您使用的 utf 字符在 utf 数据库中定义为字母。

>>> ord("ǃ")
   451

Wikipedia List of UTF characters,字符ǃ属于Latin Extended B,这就是为什么isalpha返回True

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...