Python - Check if a String is Alphanumeric
In Python, we can use the string'sisalnum()method to determine whether a string contains only letters and digits. If all characters in the string are letters or digits, it returnsTrue, otherwise it returnsFalse。
Example
def is_alphanumeric(s):
return s.isalnum()
# Test
test_string1 = "Hello123"
test_string2 = "Hello 123"
test_string3 = "Hello@123"
print(is_alphanumeric(test_string1)) # Outputs True
print(is_alphanumeric(test_string2)) # Outputs False
print(is_alphanumeric(test_string3)) # Outputs False
return s.isalnum()
# Test
test_string1 = "Hello123"
test_string2 = "Hello 123"
test_string3 = "Hello@123"
print(is_alphanumeric(test_string1)) # Outputs True
print(is_alphanumeric(test_string2)) # Outputs False
print(is_alphanumeric(test_string3)) # Outputs False
Code explanation:
is_alphanumeric(s)The function accepts a stringsas a parameter.s.isalnum()is a built-in method of strings, used to check whether a string contains only letters and digits.- If the string
scontains only letters and digits,isalnum()returnsTrue, otherwise it returnsFalse。 - We tested three different strings:
"Hello123"、"Hello 123"and"Hello@123", and output whether each is an alphanumeric string.
Output result:
True False FalseOther Extensions
Python3 Examples