Python String isascii() Method
The str.isascii()
method returns True
if all the characters in the string are ASCII or if it's an empty string; otherwise, it returns False
. ASCII characters have code points in the range U+0000-U+007F.
What are ASCII Characters?
ASCII stands for American Standard Code for Information Interchange and is a character encoding standard for electronic communication.
The original ASCII was a 7-bit character set that consisted of 128 standard ASCII Characters (0-127), and later it was extended to 256 characters (128-255). Extended ASCII means an eight-bit character encoding that includes (most of) the seven-bit ASCII characters plus additional characters.
Note: Python considers the original ASCII 7-bit character set consisting of 127 characters (0-127).
Example:
text = "Hello 2023"
print(text.isascii())
Output
True
Syntax
The Syntax of the str.isascii()
function is:
str.isascii()
Here, str
is a string.
Parameters
The str.isascii()
function takes no parameters.
Return Value
The str.isascii()
function returns:
True
if all the characters in a string are ASCII characters.False
if the string has at least one NON-ASCII character.
Example 1: Check if a given string is valid ASCII
In the example below, all the characters, numbers, and special characters in the string are valid ASCII characters; hence, the isascii()
method returns True
.
# Verify Characters
text = "Python"
print(text.isascii())
# Numbers in string format
text = "1234567890"
print(text.isascii())
# Alphanumeric with space
text = "Python 3.0"
print(text.isascii())
Output
True
True
True
Example 2: Working with isascii()
on unicode
The isascii()
method returns True
if the Unicode character is a valid ASCII character within a range (0-127) otherwise, it returns False
# Unicode character A
text = u"\u0041"
print(text.isascii())
# Unicode character s
text = u"\u0073"
print(text.isascii())
# Unicode character £
text = u"\u00a3"
print(text.isascii())
# Unicode character ©
text = u"\u00a9"
print(text.isascii())
Output
True
True
False
False
Example 3: Working with isascii()
method on Extended ASCII charset
The extended ASCII character set is not considered a valid ASCII in Python. So you can see that the Sybmol €
and ©
are considered invalid ASCII characters. Likewise, the German text Weiße Farbe
has a non-ASCII character ß
in between; hence, the string is not considered a valid ASCII.
# ASCII Extended Euro
text = "€"
print(text.isascii())
# ASCII Extended Copyright
text = "©"
print(text.isascii())
# German Character in between
text = "Weiße Farbe"
print(text.isascii())
Output
False
False
False
Reference: Python Official Docs