Skip to content Skip to sidebar Skip to footer

Python: Is Isalnum() The Same As Isalpha With Isdigit?

Is there a way to concretely verify this? I tried to solve a coding question but it seems one of the test cases (not revealed to me) takes this as wrong. In what kinds of cases doe

Solution 1:

There are cases when both isalpha and isdigit returns False, but isalnum returns True. So isalnum is not just a combination of the other two.

>>> 'a1'.isalpha(), 'a1'.isdigit(), 'a1'.isalnum()
(False, False, True)

Solution 2:

From the documentation of Python 3:

str.isalnum()Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise. A character c is alphanumeric if one the following returns True: c.isalpha(), c.isdecimal(), c.isdigit(), or c.isnumeric().

So it is not the same as isalpha() nor isdigit().

Solution 3:

According to Python 2.7 Documentation

str.isalnum()               Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise.

According to Python 3.6.6 Documentation

str.isalnum()               Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise. A character c is alphanumeric if one of the following returns True: c.isalpha(), c.isdecimal(), c.isdigit(), or c.isnumeric().

Here are few tests for isalnum() in python v3.6.6

>>> "alpha".isalnum()
True>>> "alpha10".isalnum()
True>>> "alpha%&@".isalnum()
False>>> "alpha %&@".isalnum()
False>>> "alpha with space".isalnum()
False

In first test "alpha".isalnum() returns True

And in isalpha() test, results are like this:

>>> "alpha".isalpha()
True>>> "alpha10".isalpha()
False>>> "alpha%&@".isalpha()
False>>> "alpha %&@".isalpha()
False>>> "alpha with space".isalpha()
False

So the problem is that isalnum() and isalpha() both returns True when a string contains only characters

>>> "alpha".isalnum()
True>>> "alpha".isalpha()
True

Post a Comment for "Python: Is Isalnum() The Same As Isalpha With Isdigit?"