Python – Filter Strings within ASCII range

PythonServer Side ProgrammingProgramming

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 −


 Live Demo

my_string = "Hope you are well"

print("The string is :")

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

if(my_result == True):
   print("The string contains ASCII characters")
   print("The string doesn't contain all ASCII characters")


The string is :
Hope you are well
The string contains ASCII characters


  • 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.

Updated on 04-Sep-2021 10:54:15