Last modified: Feb 23, 2026 By Alexander Williams

Convert Character to Int in Python: ord() & chr()

Working with text is common in programming.

Sometimes you need to know the numeric code behind a letter or symbol.

In Python, converting a character to an integer is simple.

You use the built-in ord() function.

This guide explains how it works.

We will also cover the reverse process.

Understanding Character Encoding

Computers store everything as numbers.

Characters like 'A' or '5' are represented by specific numeric codes.

This mapping is called character encoding.

The most common system is Unicode, specifically UTF-8.

It assigns a unique number, a code point, to every character.

For a deeper dive into how Python handles text, see our Python Character Encoding Guide for Beginners.

The ord() Function: Character to Integer

The ord() function is your main tool.

It takes a single character string as an argument.

It returns the Unicode code point (integer) for that character.

Its syntax is straightforward: ord('c').


# Basic examples of ord() function
print(ord('a'))
print(ord('Z'))
print(ord('7'))
print(ord('€'))  # A Unicode symbol
    

97
90
55
8364
    

The output shows the integer for each character.

Lowercase 'a' is 97. Uppercase 'Z' is 90.

The digit '7' is 55. The Euro symbol '€' is 8364.

Important: You must pass a string of exactly one character.

Handling Errors with ord()

What happens if you break the rule?

Passing an empty string or a longer string causes a TypeError.


# These will cause errors
# ord('')    # TypeError: ord() expected a character, but string of length 0 found
# ord('hello') # TypeError: ord() expected a character, but string of length 5 found
    

Always ensure your input is a single character.

You can check the length first.


my_char = 'A'
if len(my_char) == 1:
    code = ord(my_char)
    print(f"The code for '{my_char}' is {code}")
else:
    print("Please provide a single character.")
    

The code for 'A' is 65
    

The chr() Function: Integer to Character

The reverse operation is just as important.

The chr() function converts an integer back to its character.

It takes a Unicode code point and returns the corresponding string.


# Using chr() to convert integers back to characters
print(chr(97))
print(chr(90))
print(chr(8364))
    

a
Z
€
    

Together, ord() and chr() are perfect inverses.

chr(ord('x')) will always return 'x'.

Practical Use Cases and Examples

Why convert characters to integers?

It is useful in many real-world scenarios.

1. Finding Character Position in Alphabet

You can calculate a letter's position.

Lowercase 'a' starts at 97. So subtract 96 to get position 1.


def letter_position(letter):
    """Returns 1 for 'a', 2 for 'b', etc."""
    if len(letter) == 1 and letter.isalpha():
        # Convert to lowercase for consistent calculation
        return ord(letter.lower()) - 96
    else:
        return None

print(letter_position('c'))
print(letter_position('Z'))
    

3
26
    

2. Creating Simple Character Shift Ciphers (Caesar Cipher)

A classic use is basic encryption.

You shift each letter's code by a fixed amount.


def caesar_cipher(text, shift):
    """Encrypts text by shifting letters."""
    result = ""
    for char in text:
        if char.isalpha():
            # Determine the base ('a' or 'A')
            base = ord('A') if char.isupper() else ord('a')
            # Shift the character, wrapping around the alphabet
            shifted_char = chr((ord(char) - base + shift) % 26 + base)
            result += shifted_char
        else:
            result += char  # Keep non-letters as-is
    return result

message = "Hello, World!"
encrypted = caesar_cipher(message, 3)
decrypted = caesar_cipher(encrypted, -3)

print(f"Original: {message}")
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")
    

Original: Hello, World!
Encrypted: Khoor, Zruog!
Decrypted: Hello, World!
    

3. Data Validation and Sanitization

You can check if a character falls within a specific range.

This is useful for filtering input.


def is_printable_ascii(char):
    """Checks if a character is a standard printable ASCII character."""
    code = ord(char)
    # Printable ASCII range is 32 (space) to 126 (~)
    return 32 <= code <= 126

print(is_printable_ascii('A'))  # True
print(is_printable_ascii(' '))  # True
print(is_printable_ascii('€'))  # False (outside standard ASCII)
    

True
True
False
    

Common Pitfalls and Best Practices

Be aware of these common issues.

First, remember ord() needs a single character.

Passing more will crash your program.

Second, Unicode has many code points.

Not all integers are valid for chr().

Passing an invalid code point raises a ValueError.


# This will cause an error for some Python versions/ranges
# chr(-1)  # ValueError: chr() arg not in range(0x110000)
    

Third, encoding matters when dealing with files or networks.

The integer from ord() is the Unicode code point.

The byte representation depends on the encoding (like UTF-8).

Our guide on Python character encoding explains this in detail.

Always validate your input before using these functions.

Conclusion

Converting between characters and integers is a fundamental skill.

Python makes it easy with ord() and chr().

Use ord('c') to get the Unicode integer for a character.

Use chr(99) to get the character for a Unicode integer.

These functions are essential for text processing, encryption, and validation.

Remember the key rule: ord() takes exactly one character.

Now you can confidently work with the numeric heart of text in Python.