# Python – Filter Strings within ASCII range

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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 04-Sep-2021 10:54:15