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.

Syntax: 

string.isascii()

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"
print(s.isascii())
# Output: True

s = "Hello €"
print(s.isascii())
# 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()]
print(ascii_strings)

Example 2

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *