Explain Codes LogoExplain Codes Logo

How to get the ASCII value of a character

python
ascii-manipulation
ord
chr
Alex KataevbyAlex Kataev·Dec 19, 2024
TLDR

In Python, you can fetch a character's ASCII value using ord():

print(ord('A')) # 65 because 'A' is always on a power trip.

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():

print(chr(65)) # 'A' because 'A' donned the invisibility cloak.

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:

print(chr(65)) # 'A' because 'A' was just playing hide and seek.

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.

print(ord('👻')) # 128123 because even ghosts have tags in the Python world. print(chr(128123)) # '👻' because you can’t keep a good ghost hidden.

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.

# Correct usage print(ord('Z')) # 90 because Z just wants to be at the top once. # Incorrect usage, raises TypeError print(ord('Hello')) # 'Hey! One at a time, please!'

For conversions of entire words or sentences, cleverly use string iteration and list comprehensions:

ascii_values = [ord(char) for char in 'Python'] print(ascii_values) # [80, 121, 116, 104, 111, 110] because Python got a numeric tattoo.

Why ASCII manipulation?

Get creative with these ASCII manipulation strategies:

  1. Secret Keepers: ASCII values are perfect for encryption algorithms!
  2. Data Exchange: Morph your data for transport or storage with ASCII encoding.
  3. 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.