Python

Python String isascii() Method

The “isascii()” method in Python is used to determine the ASCII characters in a string. The abbreviation for ASCII is “American Standard Code for Information Interchange”. ASCII characters, which include letters, numbers, punctuation marks, and special symbols are represented by values ranging from 0 to 127. It is particularly relevant when dealing with text data and encoding or compatibility difficulties.

This blog will describe the “isascii()” method of Python.

Explain the “isascii()” Method in Python

The “isascii()” method in Python is a pre-built string method that is used for checking whether all the provided string characters are ASCII characters or not. It is called on the string object to check whether all the characters in that string are ASCII characters. If all the characters are ASCII, it will give a boolean value “true”.

Example 1

First, create a string type variable named “input_str” that stores a string “Linuxhint”:

input_str = "Linuxhint"

Call the “isascii()” method on the string object and store the result in the variable “resultant_str”:

resultant_str = input_str.isascii()

Lastly, print the result on the console using the “print()” method:

print("The input string is in ASCII = ", resultant_str)

As you can see the output shows “True” which indicates that the string contains ASCII characters:

Example 2

Here, we will use a numeric value as a string and check whether the string contains an ASCII character or not using the “isascii()” method:

input_str = "018"

resultant_str = input_str.isascii()

print("The input string is in ASCII = ", resultant_str)

The numeric string contains ASCII characters as it prints “True”:

Example 3

As we know all letters, numbers, special characters, and punctuation marks are ASCII characters. Let’s see if the empty string is an ASCII or not:

input_str = ""

resultant_str = input_str.isascii()

print("The input string is in ASCII = ", resultant_str)

Output

The above output indicates that the empty string is also an ASCII character.

That was all about the “isascii()” method in Python.

Conclusion

The “isascii()” method in Python is a pre-built string method that is used for checking whether all the provided string characters are ASCII characters or not. ASCII characters, such as numbers, letters, punctuation marks, and special symbols are represented by values ranging from 0 to 127. This blog described the “isascii()” method of Python.

About the author

Maria Naz

I hold a master's degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.