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

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

Check if a string is in ASCII in Python

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

主程序
my_str = 'bobbyhadz.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('bobby'.isascii()) # 👉️ True print('bobby hadz'.isascii()) # 👉️ True print(''.isascii()) # 👉️ True print('ab фг'.isascii()) # 👉️ False

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

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

主要的
print(''.isascii()) # 👉️ True print('BOBBY'.isascii()) # 👉️ True print('BOBBY HADZ'.isascii()) # 👉️ True print('BOBBY_HADZ!.?'.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. 捕获块中的潜在UnicodeEncodeError异常except
  3. 如果该str.encode()方法成功运行,则字符串为 ASCII 格式。
主程序
def is_ascii(string): try: string.encode('ascii') except UnicodeEncodeError: return False else: return True print(is_ascii('bobby')) # 👉️ True print(is_ascii('bobby hadz')) # 👉️ True print(is_ascii('')) # 👉️ True print(is_ascii('ab фг')) # 👉️ False

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

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

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

如果字符串不能用 ASCII 编码编码成字节,
UnicodeEncodeError则引发 a 并在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('bobby')) # 👉️ True print(is_ascii('bobby hadz')) # 👉️ 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('bobby')) # 👉️ True print(is_ascii('bobby hadz')) # 👉️ True print(is_ascii('')) # 👉️ True print(is_ascii('ab фг')) # 👉️ False

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

发表评论