Python String isascii()

Python String isascii() method

Python String isascii() method is used to check if the string is empty or if all characters in the string are ASCII.

ASCII characters have Unicode code points in the range U+0000 to U+007F. The decimal range is from 0 to 127. Hex range is from 0x00 to 0x7F.

You may refer this link: https://ss64.com/ascii.html, for the ASCII table with the hex values.

Consider that given string is in x.

x = "Hello World"

Then the return value of x.isascii() is

True

In this tutorial, you will learn the syntax and usage of String isascii() method in Python language.

Syntax of isascii() method

The syntax of String isascii() method in Python is given below.

str.isascii()

Parameters

The string isascii() method takes no parameters.

Return value

The string isascii() method returns a boolean value of True if the given string is empty or if all characters in the string are ASCII, otherwise False.

Examples

1. Checking if given string is ASCII in Python

In this example, we take a string value in variable x. We have to check if all characters in the string are ASCII characters.

Call isascii() method on the string object x and use the returned value as a condition in Python if else statement as shown in the following program.

Since all characters in the string are ASCII, isascii() method returns True, and the if-block executes.

Python Program

x = "Hello World"

if x.isascii():
    print('Given string is ASCII.')
else:
    print('Given string is NOT ASCII.')
Run Code Copy

Output

Given string is ASCII.

In the following program, we take a string value in variable x such that the string contains some of the non-ascii characters in the string like © symbol.

Since, not all characters in the string are ASCII, isascii() method returns False, and the else-block executes.

Python Program

x = "© Hello World"

if x.isascii():
    print('Given string is ASCII.')
else:
    print('Given string is NOT ASCII.')
Run Code Copy

Output

Given string is NOT ASCII.

4. Checking if an empty string is ASCII in Python

In the following program, we take an empty string value in variable x, and check if this empty string is ASCII.

We have already discussed in the introduction, that isascii() method returns True if the string is empty.

Python Program

x = ""

if x.isascii():
    print('Given string is ASCII.')
else:
    print('Given string is NOT ASCII.')
Run Code Copy

Output

Given string is ASCII.

Summary

In this tutorial of Python String Methods, we learned about String isascii() method, its syntax, and examples.

Related Tutorials

Code copied to clipboard successfully 👍