我想检查一个字符串是否是ASCII格式的。

我知道ord(),但是当我尝试ord('é')时,我有TypeError: ord()期望一个字符,但发现长度为2的字符串。我知道这是由我构建Python的方式引起的(如ord()的文档所解释的那样)。

还有别的办法吗?


当前回答

def is_ascii(s):
    return all(ord(c) < 128 for c in s)

其他回答

Python中的sting (str-type)是一系列字节。仅仅通过查看字符串无法判断这一系列字节是否代表ascii字符串、像ISO-8859-1这样的8位字符集的字符串,还是用UTF-8或UTF-16或其他编码的字符串。

但是,如果您知道使用的编码,那么您可以将str解码为unicode字符串,然后使用正则表达式(或循环)检查它是否包含您所关心的范围之外的字符。

Vincent Marchetti的想法是正确的,但是str.decode在Python 3中已被弃用。在Python 3中,你可以使用str.encode进行相同的测试:

try:
    mystring.encode('ascii')
except UnicodeEncodeError:
    pass  # string is not ascii
else:
    pass  # string is ascii

注意,您想要捕获的异常也从UnicodeDecodeError更改为UnicodeEncodeError。

我使用以下方法来确定字符串是ascii还是unicode:

>> print 'test string'.__class__.__name__
str
>>> print u'test string'.__class__.__name__
unicode
>>> 

然后使用一个条件块来定义函数:

def is_ascii(input):
    if input.__class__.__name__ == "str":
        return True
    return False

这样做怎么样?

import string

def isAscii(s):
    for c in s:
        if c not in string.ascii_letters:
            return False
    return True

就像@RogerDahl的回答一样,但是通过否定字符类和使用搜索而不是find_all或match来短路更有效。

>>> import re
>>> re.search('[^\x00-\x7F]', 'Did you catch that \x00?') is not None
False
>>> re.search('[^\x00-\x7F]', 'Did you catch that \xFF?') is not None
True

我想正则表达式对此进行了很好的优化。