Python Check Whether a String Is Alphanumeric
In Python, we can use the string's isalnum() method to determine whether a string contains only letters and digits. If all characters in the string are letters or digits, it returns True; otherwise, returns False。
Example
def
is_alphanumeric
(
s
)
:
return
s.
isalnum
(
)
Testing
test_string1
=
"Hello123"
test_string2
=
"Hello 123"
test_string3
=
"Hello@123"
(
is_alphanumeric
(
test_string1
)
)
Output True
(
is_alphanumeric
(
test_string2
)
)
Output False
(
is_alphanumeric
(
test_string3
)
)
Output False
Code analysis:
is_alphanumeric(s)The function takes a stringsas its argument.s.isalnum()is a built-in string method used to check whether a string contains only letters and digits.- If the string
scontains only letters and digits,isalnum()ReturnTrue; otherwise, returnsFalse。 - We tested three different strings:
"Hello123"、"Hello 123"and"Hello@123", printing whether each one is an alphanumeric string.
Output result:
True
False
False
Python3 Examples