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

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

还有别的办法吗?


当前回答

import re

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

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

其他回答

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

Python 3.7新增功能(bpo32677)

不再对字符串进行烦人/低效的ascii检查,新的内置str/bytes/bytearray方法- .isascii()将检查字符串是否为ascii。

print("is this ascii?".isascii())
# True

您可以使用正则表达式库,它接受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

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。