Python – 过滤 ASCII 范围内的字符串
pythonserver side programmingprogramming更新于 2025/10/7 5:32:17
当需要过滤 ASCII 范围内的字符串时,使用有助于 Unicode 表示的 ‘ord’ 方法和 ‘all’ 运算符。
下面是相同的演示 −
示例
my_string = "Hope you are well"
print("The string is :")
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")
输出
The string is : Hope you are well The string contains ASCII characters
解释
定义一个字符串并显示在控制台上。
对字符串中的每个字母调用‘ord’方法,并检查其 Unicode 值是否小于 128。
如果所有元素的 Unicode 表示都小于 128,则返回布尔值‘True’值被分配。
迭代完成后,将检查此布尔值。
根据此值,在控制台上显示相关信息。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

