Python - 过滤 ASCII 范围内的字符串

当需要过滤 ASCII 范围内的字符串时,将使用有助于 Unicode 表示的 'ord' 方法和 'all' 运算符。

以下是相同的演示 -

示例

my_string = "Hope you are well"

print("字符串是:")
print(my_string)

my_result = all(ord(c) < 128 for c in my_string)

if(my_result == True):
   print("The string contains ASCII characters")
else:
   print("The string doesn't contain all ASCII characters")
输出结果
字符串是:
Hope you are well
The string contains ASCII characters

解释

  • 一个字符串被定义并显示在控制台上。

  • 对字符串中的每个字母调用 'ord' 方法,并检查其 Unicode 值是否小于 128。

  • 如果所有元素的 Unicode 表示都小于 128,则分配一个布尔值“真”。

  • 一旦迭代完成,就会检查这个布尔值。

  • 根据该值,在控制台上显示相关消息。