Compare Unicode code point range in Python3

Viewed 111

I would like to check if a character is in a certain Unicode range or not, but seems I cannot get the expected answer.

char = "?" # the unicode value is 0xff1f
print(hex(ord(char)))
if hex(ord(char)) in range(0xff01, 0xff60):
    print("in range")
else:
    print("not in range")

It should print: "in range", but the results show: "not in range". What have I done wrong?

3 Answers

hex() returns a string. To compare integers you should simply use ord:

if ord(char) in range(0xff01, 0xff60):

You could've also written:

if 0xff01 <= ord(char) < 0xff60:

In general for such problems, you can try inspecting the types of your variables.

Typing 0xff01 without quotes, represents a number.

list(range(0xff01, 0xff60)) will give you a list of integers [65281, 65282, .., 65375]. range(0xff01, 0xff60) == range(65281, 65376) evaluates to True.

ord('?') gives you integer 65311.

hex() takes an integer and converts it to '0xff01' (a string).

So, you simply need to use ord(), no need to hex() it.

Just only use ord:

if ord(char) in range(0xff01, 0xff60):
    ...

hex is not needed.

As mentioned in the docs:

Convert an integer number to a lowercase hexadecimal string prefixed with “0x”.

Obviously that already describes it, it becomes a string instead of what we want, an integer.

Whereas the ord function does what we want, as mentioned in the docs:

Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().

Related