Junior
How to check that a string contains only digits or letters?
sobes.tech AI
Answer from AI
Use the methods .isalnum(), .isdigit(), .isalpha().
.isalnum() checks if the string consists only of letters and digits.
# Example of using .isalnum()
str_alnum = "abc123"
str_not_alnum = "abc 123"
print(str_alnum.isalnum()) # True
print(str_not_alnum.isalnum()) # False
.isdigit() checks if the string consists only of digits.
# Example of using .isdigit()
str_digit = "123"
str_not_digit = "abc123"
print(str_digit.isdigit()) # True
print(str_not_digit.isdigit()) # False
.isalpha() checks if the string consists only of letters.
# Example of using .isalpha()
str_alpha = "abc"
str_not_alpha = "abc123"
print(str_alpha.isalpha()) # True
print(str_not_alpha.isalpha()) # False
You can combine these methods for more complex checks. For example, to check if a string contains only digits OR only letters:
# Check for only digits OR only letters
str_only_digits = "123"
str_only_letters = "abc"
str_mixed = "abc123"
print(str_only_digits.isdigit() or str_only_letters.isalpha()) # True
print(str_only_letters.isdigit() or str_only_letters.isalpha()) # True
print(str_mixed.isdigit() or str_mixed.isalpha()) # False