When it is required to filter strings within the ASCII range, the ‘ord’ method that helps with Unicode representation and the ‘all’ operator are used.
Below is a demonstration of the same −
Example
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")
Output
The string is : Hope you are well The string contains ASCII characters
Explanation
A string is defined and is displayed on the console.
The ‘ord’ method is called on every letter in the string, and checked to see if its Unicode value is less than 128.
If all the elements have Unicode representation less than 128, a Boolean ‘True’ value is assigned.
Once the iteration is complete, this Boolean value is checked.
Based on this value, relevant message is displayed on the console.