strings ord python

1. How to Convert Characters and ASCII Values

Python provides two primary built-in functions for this conversion:

  • ord(character) (Ordinal): Takes a single character as a string and returns its corresponding integer ASCII (or Unicode) value
  • chr(integer) (Character): Takes an integer ASCII value and returns the corresponding character.

Python

# Character to ASCII
print(ord('A'))  # Output: 65
print(ord('a'))  # Output: 97
print(ord('0'))  # Output: 48
 
# ASCII to Character
print(chr(65))   # Output: 'A'
print(chr(97))   # Output: 'a'
print(chr(32))   # Output: ' ' (space)

2. Important ASCII Ranges to Remember

The standard ASCII table contains 128 characters (0–127). Here are the most common ranges you will encounter in programming:

CategoryCharacter RangeASCII Decimal Range
Digits'0' to '9'48 to 57
Uppercase Letters'A' to 'Z'65 to 90
Lowercase Letters'a' to 'z'97 to 122
WhitespaceSpace (' '), Tab, Newline32, 9, 10

Pro Tip: Notice that uppercase and lowercase letters are separated by a distance of 32 in their ASCII values (e.g., ord('a') is 97, and ord('A') is 65; ).

3. Practical Use Cases and Tricks

A. Case Conversion via Math

Because of the predictable 32-character gap between uppercase and lowercase letters, you can manually toggle case using ASCII math:

Python

# Convert lowercase to uppercase by subtracting 32
char = 'b'
upper_char = chr(ord(char) - 32)
print(upper_char)  # Output: 'B'

(Note: In real-world Python, you would usually just use char.upper(), but understanding the underlying ASCII math is great for algorithmic problems!)

B. Checking Character Types

You can use ASCII ranges to check character types manually, though Python has built-in string methods like .isdigit() and .isalpha() for this:

Python

char = '7'
if 48 <= ord(char) <= 57:
    print("It's a digit!")

4. Important Things to Know About Python & ASCII

  • Unicode vs. ASCII: Python strings are fully Unicode-based (specifically UTF-8). However, ord() and chr() are fully backward-compatible with ASCII. For the first 128 characters (0–127), Unicode and ASCII are identical.

  • String Iteration: You can easily map an entire string to its ASCII values using a list comprehension:

    Python

    ascii_list = [ord(c) for c in "Hello"]
    print(ascii_list)  # Output: [72, 101, 108, 108, 111]

If you look at an ASCII chart between Z (90) and a (97), those 6 missing slots aren’t empty space—they are filled with common punctuation marks:

  • [ (91)

  • \ (92)

  • ] (93)

  • ^ (94)

  • _ (95)

  • ` (96)