How to check if a string contains all ASCII characters in Python

In this shot, we are going to use the isascii() function in Python to check whether a string contains all ASCII characters. The American Standard Code for Information Interchange (ASCII) is a character encoding standard which uses numbers from 0 to 127 which represent English characters. For example, ASCII code for the character A is 65, and the code for a is 97.

Syntax

The syntax of the isascii() function is shown below:

str.isascii()

Parameters

The isascii() function does not accept any parameters.

Return value

The isascii() function returns a boolean value where True indicates that the string contains all ASCII characters and False indicates that the string contains some non-ASCII characters.

Code

Let’s have a look at the code now.

s1 = "I enjoy coding in PythØn"
s2 = "Hello, this is Educative!"
print("S1: ", s1.isascii())
print("S2: ", s2.isascii())

Explanation:

  • In lines 1 and 2, we define two strings: one with a non-ASCII character (Ø) and the other with all ASCII characters.

  • In lines 4 and 5, we printed whether the two strings contain any non-ASCII characters. We can see in the output that the first string contains one non-ASCII character and so the output is False. The second string contains all the ASCII characters and so the output is True.

In this way, we can check whether our string contains any non-ASCII characters.