How to get the ASCII value of a character
In Python, you can fetch a character's ASCII value using ord()
:
The ord()
function converts a single character like 'A'
to its corresponding ASCII integer.
To reverse the process, that is, convert an ASCII value back to its character form, use chr()
:
Python 3 prefers equality and unity. As such, chr()
is used for all Unicode characters, replacing Python 2's unichr()
. It covers all valid Unicode points ranging from 0
to 0x10FFFF
.
Reversal: Converting ASCII to Character
If you got the ASCII value but lost the character— no worries, mate! Python’s chr()
will help you find it:
In Python 3, chr()
is your best friend handling the conversion of ASCII back to character. In Python 2, this friend was unichr()
.
Those Fancy Emojis and Special Characters
We live in a world with emojis and special characters. ord()
and chr()
won't leave them behind, handling Unicode values beyond the traditional ASCII range.
Remember to ensure that your encoding is spot-on when waving your wand at characters outside the traditional ASCII range (0-127).
Common Mistakes to Beware of
If you push ord()
's boundaries by throwing more than one character at it, it will push back with a TypeError
. Treat it kindly with a single character.
For conversions of entire words or sentences, cleverly use string iteration and list comprehensions:
Why ASCII manipulation?
Get creative with these ASCII manipulation strategies:
- Secret Keepers: ASCII values are perfect for encryption algorithms!
- Data Exchange: Morph your data for transport or storage with ASCII encoding.
- User's Manual: Track non-printable or control characters in user input with ASCII for validation checks.
Handle Encoding Smartly
In modern Python, ord()
now returns Unicode code points. It's smart to handle the character set correctly when working with extended ASCII or Unicode.
ASCII: A practical approach
Extend the reach of ord()
and chr()
to:
- Strike a conversation with the user through keyboard inputs.
- Create interesting sequences of characters like alphabets or passwords.
- Be the file encoding master where bytes correlate to characters.
Was this article helpful?