How can I check if a string contains only ASCII characters in Python?
Gable E
To check if a string contains only ASCII characters in Python, you can iterate over each character in the string and check if its Unicode code point is within the ASCII range (0-127).
Here's an example of how you can perform this check:
1
2
3
4
5
6
7
8
9
10
11
12
13
def is_ascii(string):
for char in string:
if ord(char) > 127:
return False
return True
# Usage:
input_string = input("Enter a string: ")
if is_ascii(input_string):
print("The string contains only ASCII characters.")
else:
print("The string contains non-ASCII characters.")
In the above code, theis_ascii() function takes astring parameter to check. It iterates over each character in the string and uses theord() function to obtain the Unicode code point of each character. If the code point of any character is greater than 127, it indicates that the character is outside the ASCII range, and the function returnsFalse. If all characters have code points within the ASCII range, the function returnsTrue.
You can use theis_ascii() function by providing a string as an argument. It will check if the string contains only ASCII characters by examining the Unicode code point of each character. The result is then printed accordingly.
It's important to note that this approach checks if all characters in the string have code points within the ASCII range. However, it does not account for other character encodings or Unicode characters beyond the ASCII range. If you need to handle non-ASCII characters or work with different encodings, you may consider using libraries or functions specifically designed for character encoding and Unicode handling, such as theunicodedata module.