Python String isascii()
Method
The isascii() method in Python checks whether all the characters in a string are ASCII characters (i.e., in the range 0 to 127).
It returns True
if all characters are ASCII, otherwise False
. This method is available from Python 3.7 and later.
Syntax
string.isascii()
Parameters:
- No parameters are required.
Returns:
True
– If all characters in the string are ASCII.False
– If at least one character is not an ASCII character.
Example 1: Simple ASCII String
text = "Hello123"
print(text.isascii())
True
Example 2: String with Unicode Characters
text = "Café"
print(text.isascii())
False
The character é
is not an ASCII character.
Example 3: Empty String
text = ""
print(text.isascii())
True
An empty string is considered ASCII.
Use Cases
- Validating user input for systems that only support ASCII
- Pre-processing text before encoding or sending to legacy systems
- Detecting presence of special or non-English characters
Common Mistakes
- Assuming
isascii()
checks if a string contains only letters or digits. It doesn’t—it allows symbols, punctuation, and whitespace too, as long as they’re ASCII. - Using it in Python versions earlier than 3.7 will raise an
AttributeError
.
Interview Tip
If you’re asked to filter out non-ASCII characters from a string, isascii()
can help quickly detect such cases or be used in list comprehensions to clean strings.
Summary
string.isascii()
checks if all characters are in the ASCII range.- Returns
True
for ASCII-only strings,False
otherwise. - Empty strings return
True
. - Available in Python 3.7+
Practice Problem
Write a program that checks if user input contains only ASCII characters.
text = input("Enter some text: ")
if text.isascii():
print("All characters are ASCII.")
else:
print("Non-ASCII characters found!")