How can I check if a string contains only ASCII letters and digits in Python?
Alex K
To check if a string contains only ASCII letters and digits in Python, you can use theisalnum() method and theord() function. Here's a long-form explanation of how to achieve this:
1. Check the string:
- Iterate over each character in the string using a loop or a comprehension.
- Use theord() function to obtain the Unicode code point of each character.
- Theord() function returns an integer representing the Unicode code point of the character.
- Compare the obtained code point with the ASCII ranges for letters and digits.
- For ASCII letters, valid code points fall within the ranges of 65 to 90 (uppercase) and 97 to 122 (lowercase).
- For ASCII digits, valid code points fall within the range of 48 to 57.
- If the code point falls within these ranges, the character is either an ASCII letter or digit.
- If any character in the string does not satisfy this condition, the string is not comprised only of ASCII letters and digits.
- Example:
1
2
3
def contains_only_ascii_letters_and_digits(string):
return all(65 <= ord(char) <= 90 or 97 <= ord(char) <= 122 or 48 <= ord(char) <= 57 for char in string)
2. Use the function:
- Call thecontains_only_ascii_letters_and_digits() function and pass the string you want to validate.
- It will returnTrue if the string contains only ASCII letters and digits, andFalse otherwise.
- Example:
By using theord() function to obtain the Unicode code point of each character and checking if it falls within the appropriate ASCII ranges, you can efficiently validate if a string contains only ASCII letters and digits. This approach allows for concise and flexible validation based on the character's Unicode code point.