Python – Filter Strings within ASCII range



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

 Live Demo

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.

Updated on: 2021-09-04T10:54:15+05:30

332 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements