在 Python 中检查字符串是否为 ASCII

使用 str.isascii() 方法检查字符串是否为 ASCII,例如 if my_str.isascii():。 如果字符串为空或字符串中的所有字符都是 ASCII,则 str.isascii() 方法返回 True,否则返回 False。

my_str = 'www.zadmei.com'

if my_str.isascii():
    # ?️ this runs
    print('The string contains only ASCII characters')
else:
    print('The string does NOT contain only ASCII characters')


print('zadmei'.isascii())  # ?️ True
print('www zadmei'.isascii())  # ?️ True
print(''.isascii())  # ?️ True

print('ab фг'.isascii())  # ?️ False

在 Python 中检查字符串是否为 ASCII

我们使用 str.isascii() 方法来检查字符串是否仅包含 ASCII 字符。

如果字符串为空或字符串中的所有字符都是 ASCII,str.isascii 方法返回 True,否则返回 False

print(''.isascii()) # ?️ True print('ZADMEI'.isascii()) # ?️ True print('WWW ZADMEI'.isascii()) # ?️ True print('WWW_ZADMEI!.?'.isascii()) # ?️ True print('ФФФ'.isascii()) # ?️ False

ASCII 字符的代码点在 U+0000-U+007F 范围内。

如果我们认为空字符串不是 ASCII,请检查字符串的长度。

my_str = ''

if my_str.isascii() and len(my_str) > 0:
    print('The string contains only ASCII characters')
else:
    # ?️ this runs
    print('The string does NOT contain only ASCII characters')

或者,我们可以使用 try/except 语句。


使用 try/except 检查字符串是否为 ASCII

要检查字符串是否为 ASCII:

  1. 使用 str.encode() 方法使用 ASCII 编码对字符串进行编码。
  2. except 块中捕获潜在的 UnicodeEncodeError 异常。
  3. 如果 str.encode() 方法成功运行,则字符串为 ASCII。
def is_ascii(string):
    try:
        string.encode('ascii')
    except UnicodeEncodeError:
        return False
    else:
        return True


print(is_ascii('zadmei'))  # ?️ True
print(is_ascii('www zadmei'))  # ?️ True
print(is_ascii(''))  # ?️ True

print(is_ascii('ab фг'))  # ?️ False

我们使用 try/except/else 语句来检查字符串是否仅包含 ASCII 字符。

try 语句使用 str.encode() 方法将字符串编码为 ASCII 编码的字节。

str.encode 方法将字符串的编码版本作为字节对象返回。 默认编码为 utf-8。

如果字符串无法使用 ASCII 编码编码为字节,则会引发 UnicodeEncodeError 并在 except 块中进行处理。

如果 str.encode() 方法成功运行,则不会引发错误并且 else 块运行。

或者,我们可以使用 all() 函数。


使用 all() 检查字符串是否为 ASCII

要检查字符串是否为 ASCII:

  1. 使用生成器表达式迭代字符串。
  2. 检查每个字符的 Unicode 码位是否小于 128。
  3. 如果所有字符都满足条件,则字符串为 ASCII。
def is_ascii(string):
    return all(ord(char) < 128 for char in string)

print(is_ascii('zadmei'))  # ?️ True
print(is_ascii('www zadmei'))  # ?️ True
print(is_ascii(''))  # ?️ True

print(is_ascii('ab фг'))  # ?️ False

我们使用生成器表达式来迭代字符串。

生成器表达式用于对每个元素执行一些操作或选择满足条件的元素子集。

在每次迭代中,我们使用 ord() 函数来检查当前字符的 Unicode 代码点是否小于 128。

ord 函数接受一个表示 1 个 Unicode 字符的字符串,并返回一个表示给定字符的 Unicode 代码点的整数。

print(ord('a'))  # ?️ 97
print(ord('b'))  # ?️ 98

标准 ASCII 字符在 0-127 范围内,因此我们检查每个字符的 Unicode 代码点是否小于 128。

all() 内置函数将可迭代对象作为参数,如果可迭代对象中的所有元素都为真(或可迭代对象为空),则返回 True。

def is_ascii(string):
    return all(ord(char) < 128 for char in string)

print(is_ascii('zadmei'))  # ?️ True
print(is_ascii('www zadmei'))  # ?️ True
print(is_ascii(''))  # ?️ True

print(is_ascii('ab фг'))  # ?️ False

如果字符串中的所有字符都是 ASCII,则函数返回 True,否则返回 False