learn how to use python string isascii() with example

The isascii() method is a string method in Python that checks whether the string contains ASCII characters only.

ASCII (American Standard Code for Information Interchange) is a standard encoding system for computers to represent text and other characters. It uses numbers from 0 to 127 to represent all English characters as well as some non-printable control characters.



Where string is the variable holding the string you want to check. The method doesn’t require any arguments.

How to use the isascii() method:

s = "Hello"
# Output: True

s = "Hello €"
# Output: False

Example 1

Filtering out non-ASCII strings from a list.

strings = ["Hello", "Bonjour", "Guten Tag", "你好", "こんにちは"]
ascii_strings = [s for s in strings if s.isascii()]

Example 2

Checking if a string can be safely used in an ASCII-only system.

username = "user1€"
if username.isascii():
  print("Username is valid.")
  print("Username is not valid. It contains non-ASCII characters.")