Open In App

Python | Check for ASCII string

Improve
Improve
Like Article
Like
Save
Share
Report

Many times it is desirable to work with the strings that only contain alphabets and the other special characters are undesirable and sometimes this very task becomes the point to filter the strings and hence requires the way to check if a string is whole ASCII. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using ord() + all() The combination of this method can be used to achieve the desirable task. In this method, we search for all the string and check for each character, a value in range of ASCII characters. 

Python3




# Python3 code to demonstrate
# Check for ASCII string
# using all() + ord()
 
# initializing string
test_string = "G4G is best"
 
# printing original string
print("The original string : " + str(test_string))
 
# using all() + ord()
# Check for ASCII string
res = all(ord(c) < 128 for c in test_string)
 
# print result
print("Is the string full ASCII ? : " + str(res))


Output

The original string : G4G is best
Is the string full ASCII ? : True

  Method #2 : Using lambda + encode() This task can also be achieved using the above functions. In this combination, lambda function is used to extend the size check logic to whole string and encode function checks if the size of original and encoded strings match. 

Python3




# Python3 code to demonstrate
# Check for ASCII string
# using lambda + encode()
 
# initializing string
test_string = "G4G is best"
 
# printing original string
print("The original string : " + str(test_string))
 
# using lambda + encode()
# Check for ASCII string
res = lambda ele: len(ele) == len(ele.encode())
 
# print result
print("Is the string full ASCII ? : " + str(res(test_string)))


Output

The original string : G4G is best
Is the string full ASCII ? : True

Method 3: Using re.search()
re.search() is a function from the Python re (regular expression) module. It searches for a pattern (in this case, a pattern that matches any ASCII character) within a string and returns a match object if found, or None if not found.

Python




import re  # Import the re module
 
def is_ascii(string):
  # Use re.search() to search for a pattern (in this case, a pattern that matches any ASCII character)
  # within the input string. The r prefix before the pattern string tells Python to treat the string as a raw string,
  # which is useful for patterns that contain backslashes. The ^ and $ symbols indicate that the pattern should
  # match the entire string (not just a substring).
  match = re.search(r'^[\x00-\x7F]+$', string)
   
  # Return a boolean value indicating whether a match was found (True if a match was found, False if not)
  return bool(match)
 
# Test the function
test_string = "G4G is best"
print("The original string : " + str(test_string))
print("Is the string full ASCII ? :", is_ascii(test_string))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original string : G4G is best
('Is the string full ASCII ? :', True)

This function has a time complexity of O(n), where n is the length of the input string, since re.search() searches through the entire string. The auxiliary space is O(1), since the function only creates a single boolean variable to store the result.

Approach#4: Using string.printable()

The approach used here is to check whether each character in the string s is a printable ASCII character or not. We can use the string.printable constant to get all the printable ASCII characters, which includes digits, letters, punctuation, and whitespace. We can then iterate over the characters in the string s and check if each character is in string.printable using the in operator.

Algorithm

1. Define a function is_ascii that takes a string s as input.
2. Iterate over each character c in s.
3. Check if the character c is in string.printable using the in operator.
4. If any character c is not in string.printable, return False.
5. If all characters in s are in string.printable, return True

Python3




import string
 
def is_ascii(s):
    """Return True if string s is ASCII, False otherwise."""
    return all(c in string.printable for c in s)
 
# Example usage:
s = "G4G is best"
print(is_ascii(s))  # Output: True


Output

True

Time Complexity:  O(n), where n is the length of the input string s. This is because we need to iterate over each character in s once.

Space Complexity: O(1), which is constant. We are not using any additional data structures that depend on the input size. The string.printable constant is a fixed-length constant that does not depend on the length of the input string.



Last Updated : 08 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads