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

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

还有别的办法吗?


当前回答

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。

您可以使用正则表达式库,它接受Posix标准[[:ASCII:]]定义。

为了防止代码崩溃,可能需要使用try-except来捕获TypeErrors

>>> ord("¶")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found

例如

def is_ascii(s):
    try:
        return all(ord(c) < 128 for c in s)
    except TypeError:
        return False
import re

def is_ascii(s):
    return bool(re.match(r'[\x00-\x7F]+$', s))

要包含一个空字符串作为ASCII,将+改为*。

我觉得你问的问题不对

python中的字符串没有对应于'ascii'、utf-8或任何其他编码的属性。字符串的来源(无论是从文件读取,还是从键盘输入,等等)可能已经用ascii编码了一个unicode字符串来生成字符串,但这是您需要去寻找答案的地方。

也许你会问:“这个字符串是用ascii编码unicode字符串的结果吗?”——这个你可以回答 通过:

try:
    mystring.decode('ascii')
except UnicodeDecodeError:
    print "it was not a ascii-encoded unicode string"
else:
    print "It may have been an ascii-encoded unicode string"