The 'isalnum' method doesn't work properly in the code

Viewed 61

I just start learning Python a few days, and this is a silly question. I think this code should return false as the input characters are not alpha, but I don't understand why it will return true. How do I set up to make sure this method works properly. ``

word='½Ã'
if word.isalnum():
    print("it's true")
else:
    print("it's not alpha")

`` enter image description here

1 Answers

One of the characters is numeric and one of them is alpha based on the Unicode Standard, so the entire string returns True for .isalnum()

In [1]: word='½Ã'

In [2]: [w.isalpha() for w in word]
Out[2]: [False, True]

In [3]: [w.isnumeric() for w in word]
Out[3]: [True, False]

The definitions of what characters return True for each of these methods is described in the python documentation linked above.

If you are trying to test if the string only contains ASCII characters and not unicode, then you can use the .isacii() method:

In [4]: [w.isascii() for w in word]
Out[4]: [False, False]
Related