Determine the Unicode general category of a character.
How It Works
unicodedata.category(character) returns a short category code, such as Lu for uppercase letters and Nd for decimal digits. These categories help Unicode-aware processing but are not a substitute for all linguistic or security validation.
Step-by-Step Example
import unicodedata
print(unicodedata.category('A'))
print(unicodedata.category('7'))
print(unicodedata.category(' '))
Understanding the Example
- The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.
A successful run of this example prints the following output:
Lu
Nd
Zs
Where This Fits in a Real Program
Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.
Practice: Try It Yourself
Unicode categories are broader and more nuanced than ASCII character groups.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Treating one Unicode category as a complete whitelist for user identity or security decisions.
- Group the characters in a short text by their general category.
Key Takeaways
- Determine the Unicode general category of a character.
- unicodedata.category(character) returns a short category code, such as Lu for uppercase letters and Nd for decimal digits.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.