Check for ASCII String - Python
To check if a string contains only ASCII characters, we ensure all characters fall within the ASCII range (0 to 127). This involves comparing each character's value to ensure it meets the criteria.
Using str.isascii()
The simplest way to do this in Python is by using the built-in str.isascii()
method, which efficiently checks if all characters in a string belong to the ASCII character set.
s = "G4G is best" # string
# Check if all characters in 's' are ASCII characters
res = s.isascii()
print(str(res))
Output
True
Explanation: s.isascii()
checks if every character in s is an ASCII character. It returns True
if all characters are ASCII, False
otherwise.
Table of Content
Using set
By defining a set containing all ASCII characters and checking if each character in the string belongs to this set, we can determine if the string consists entirely of ASCII characters.
s = "G4G is best"
a = set(chr(i) for i in range(128)) # 'set' contains all ASCII characters
# Check if every character in string 's' is present in the set 'a'
res = all(c in a for c in s)
print(str(res))
Output
True
Explanation:
set(chr(i) for i in range(128))
):This creates seta
of all ASCII characters (0–127).all(c in a for c in s)
):This usesall()
to check if every character ins
is in the seta.
Using all()
all() function checks if all elements of an iterable are true and the ord() function returns the Unicode code point of a character. We compare each character's Unicode value with 128 to ensure it's an ASCII character.
s = "G4G is best"
res = all(ord(c) < 128 for c in s)
print(str(res))
Output
True
Explanation: all(ord(c) < 128 for c in s)
verifies if each character in s
has an ASCII value (less than 128).
Using regular expression
Regular expression defines a pattern to match specific sequences of characters in a string. For this purpose, the pattern ^[\x00-\x7F]*$ is used to verify that every character in the string falls within the ASCII range (0 to 127).
import re
s = "G4G is best"
res = bool(re.match(r'^[\x00-\x7F]*$', s))
print(str(res))
Output
True
Explanation:
^
and$
: This ensure the entire string is checked.[\x00-\x7F]
:This defines the range of valid characters: ASCII characters (0-127).*
:This allows zero or more repetitions of characters within the specified ASCII range.