How to print the ASCII value in Python
Discover multiple ways to print ASCII values in Python. Explore tips, real-world uses, and how to debug common errors in your code.

You can print a character's ASCII value for many Python tasks, like data validation and character manipulation. The built-in ord() function makes this process straightforward and efficient.
In this article, we'll show you several techniques to handle ASCII values with ord() and chr(). You'll also find real-world applications, practical tips, and debugging advice to master the concept.
Using the ord() function to get ASCII values
character = 'A'
ascii_value = ord(character)
print(f"The ASCII value of '{character}' is {ascii_value}")--OUTPUT--The ASCII value of 'A' is 65
The ord() function is Python's direct method for converting characters to integers. In the example, it processes the character 'A' and returns its ASCII value, 65. This integer is then assigned to the ascii_value variable.
This conversion is useful for several reasons:
- It allows for numerical comparisons and manipulations of characters.
- It's a key step in data validation, helping you ensure characters fall within a specific range.
Basic ASCII conversion techniques
You can expand on the basic ord() function by converting entire strings, reversing the process with chr(), and manipulating characters within specific ASCII ranges.
Converting a string to a list of ASCII values
text = "Hello"
ascii_values = [ord(char) for char in text]
print(f"ASCII values of '{text}': {ascii_values}")--OUTPUT--ASCII values of 'Hello': [72, 101, 108, 108, 111]
To convert an entire string, you can iterate through it and apply the ord() function to each character. The example uses a list comprehension, [ord(char) for char in text], which is a concise and Pythonic way to build a new list from an existing one.
- The code loops through each
charin thetextstring. - It calls
ord()on every character to get its integer value. - Finally, it collects these integers into the
ascii_valueslist.
Converting ASCII values back to characters with chr()
ascii_values = [65, 66, 67, 68]
text = ''.join(chr(value) for value in ascii_values)
print(f"ASCII values {ascii_values} converted to text: {text}")--OUTPUT--ASCII values [65, 66, 67, 68] converted to text: ABCD
The chr() function is the inverse of ord(), turning an integer back into its character representation. It's perfect for when you need to reconstruct a string from a list of ASCII values.
- The code iterates through the
ascii_valueslist using a generator expression. - For each integer,
chr()finds the matching character. - Finally, the
''.join()method stitches all the characters together into a single, readable string.
Working with ASCII ranges
# Print uppercase letters and their ASCII values
for value in range(65, 91):
print(f"{chr(value)}: {value}", end=" ")--OUTPUT--A: 65 B: 66 C: 67 D: 68 E: 69 F: 70 G: 71 H: 72 I: 73 J: 74 K: 75 L: 76 M: 77 N: 78 O: 79 P: 80 Q: 81 R: 82 S: 83 T: 84 U: 85 V: 86 W: 87 X: 88 Y: 89 Z: 90
You can work with specific character sets by iterating through their ASCII value ranges. The code uses a for loop with range(65, 91) to cycle through the integers for the uppercase letters 'A' to 'Z'. This is a handy way to generate or validate characters systematically.
- Inside the loop,
chr()converts each integer back into its character form. - The
print()function then displays each character next to its numeric value. - Using
end=" "keeps all the output on a single, neatly formatted line.
Advanced ASCII manipulation techniques
Beyond basic conversions, you can apply these concepts to create ASCII maps with dictionary comprehensions or convert values between binary and hexadecimal representations.
Using dictionary comprehensions for ASCII mapping
# Create a mapping of characters to ASCII values
text = "Python"
ascii_map = {char: ord(char) for char in text}
print(ascii_map)--OUTPUT--{'P': 80, 'y': 121, 't': 116, 'h': 104, 'o': 111, 'n': 110}
A dictionary comprehension is a concise way to build a dictionary from an iterable. The expression {char: ord(char) for char in text} creates a key-value map for each character in the string.
- The
charbecomes the dictionary key. - The result of
ord(char)becomes its corresponding value.
This method is efficient for creating a lookup table, giving you instant access to any character's ASCII value within the map.
Creating a simple ASCII table with binary representation
for i in range(33, 48):
char = chr(i)
binary = bin(i)[2:].zfill(8)
print(f"{i:3d} | {char:^3} | {binary}")--OUTPUT--33 | ! | 00100001
34 | " | 00100010
35 | # | 00100011
36 | $ | 00100100
37 | % | 00100101
38 | & | 00100110
39 | ' | 00100111
40 | ( | 00101000
41 | ) | 00101001
42 | * | 00101010
43 | + | 00101011
44 | , | 00101100
45 | - | 00101101
46 | . | 00101110
47 | / | 00101111
This loop builds a partial ASCII table, showing the decimal value, character, and its 8-bit binary equivalent. It iterates from 33 to 47, which covers common punctuation symbols. The code combines character conversion with string formatting to produce a clean output, similar to techniques used in converting binary to decimal.
- The
bin()function converts the integer to a binary string, and slicing with[2:]removes the standard0bprefix. zfill(8)pads the binary string with leading zeros to ensure it represents a full byte.- Finally, an f-string organizes the integer, character, and binary value into neatly aligned columns.
Converting between ASCII and hexadecimal values
text = "ASCII"
hex_values = [hex(ord(char)) for char in text]
print(f"Hexadecimal ASCII values of '{text}': {hex_values}")
print(f"Back to text: {''.join(chr(int(h, 16)) for h in hex_values)}")--OUTPUT--Hexadecimal ASCII values of 'ASCII': ['0x41', '0x53', '0x43', '0x49', '0x49']
Back to text: ASCII
You can also represent ASCII values in hexadecimal, a format that's common in many computing contexts. The code uses a list comprehension to iterate through the string. It chains hex(ord(char)) to convert each character first to an integer, then to a hexadecimal string like '0x41', following patterns similar to converting integers to strings.
- To reverse the process,
int(h, 16)converts the hex string back to an integer by specifying base 16. chr()then turns the integer back into a character, and''.join()reconstructs the original string from the resulting characters.
Move faster with Replit
Replit is an AI-powered development platform where all Python dependencies come pre-installed, so you can skip setup and start coding instantly. This lets you move from learning individual techniques, like using ord(), to building complete applications with Agent 4.
Describe the app you want to build, and the Agent will handle the code, databases, APIs, and deployment. You could build tools like:
- A custom text converter that transforms strings into their ASCII, binary, or hexadecimal representations.
- A data validation utility that checks if user input contains only characters from a specific ASCII range.
- A simple encryption tool that implements a Caesar cipher by shifting character codes.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
While ord() and chr() are powerful, you might encounter a few common issues with character encodings and arithmetic operations.
The ord() function processes any Unicode character, not just ASCII. This can lead to unexpected results:
- If you pass it a character like an emoji or an accented letter, it returns a Unicode code point that falls outside the standard 0–127 ASCII range.
- This isn't an error, but it can cause issues if your logic assumes ASCII-only values, leading to validation failures or incorrect calculations.
You can trigger a ValueError when using chr() if you provide an integer outside the valid Unicode range (0 to 1,114,111). This typically happens when a calculation produces a negative number or you're processing invalid data. Validating integers before passing them to chr() can prevent your program from crashing and may require code repair.
Arithmetic on ASCII values can "overflow" a character range, producing unintended symbols. For example, if you're shifting letters for a cipher and add 3 to the value of 'Y', you'll get the code for '\' instead of 'B'. To prevent this, use the modulo (%) operator to wrap your values. This ensures that shifting past 'Z' correctly loops back to the start of the alphabet at 'A'.
Handling non-ASCII characters with ord()
Handling non-ASCII characters with ord()
The ord() function works with any Unicode character, but this flexibility can be a problem if your application expects only standard ASCII. A character like 'é' will return a value above 127, which can break your validation logic.
The following code demonstrates how to detect these non-ASCII characters and raise a ValueError to handle them gracefully.
This example demonstrates using try and except for error handling:
text = "Café"
try:
for char in text:
if ord(char) > 127:
raise ValueError(f"Non-ASCII character detected: {char}")
print("Text contains only ASCII characters")
except ValueError as e:
print(e)
The loop processes the string "Café" and finds that ord('é') returns a value greater than 127. This triggers the if statement, which explicitly raises a ValueError. The code below shows how to handle this scenario gracefully.
text = "Café"
non_ascii = [char for char in text if ord(char) > 127]
if non_ascii:
print(f"Non-ASCII characters found: {non_ascii}")
ascii_only = ''.join(char for char in text if ord(char) <= 127)
print(f"ASCII-only version: {ascii_only}")
else:
print("Text contains only ASCII characters")
This solution uses a list comprehension to find characters where ord(char) is greater than 127. It collects these in a non_ascii list and, if any are found, builds a new string containing only the valid ASCII characters.
This approach is useful for sanitizing data from external sources or user input. It ensures your application can gracefully handle unexpected characters—like emojis or accented letters—when your logic requires a strict ASCII set.
Fixing incorrect ASCII to character conversion with chr()
It's a common mistake to convert a string of space-separated ASCII values directly. This can cause a ValueError because the chr() function expects a single integer, not individual characters from the string. The following code demonstrates this common pitfall.
values = "65 66 67 68"
text = ''.join(chr(int(value)) for value in values)
print(f"Converted text: {text}")
The loop iterates over each character in the string, not the complete numbers. It fails when int() receives a space instead of a digit. The corrected approach below shows how to properly parse the string first.
values = "65 66 67 68"
text = ''.join(chr(int(value)) for value in values.split())
print(f"Converted text: {text}")
The fix is to use the values.split() method. This simple change prevents a ValueError by correctly parsing the input string.
- It splits the string into a list of number strings, like
['65', '66']. - The loop then iterates over this list, allowing
int()to convert each complete number without hitting a space.
This error often happens when you process data from files or user input where numbers are space-separated.
Preventing overflow errors in ASCII arithmetic operations
When you're performing arithmetic on ASCII values, like shifting characters for a simple cipher, you can easily “overflow” the intended range. This often results in unintended symbols instead of letters. The following code demonstrates what happens when a shift operation goes too far.
message = "z{|}"
shift = 5
encrypted = ""
for char in message:
shifted_value = ord(char) + shift
encrypted += chr(shifted_value)
print(f"Original: {message}\nEncrypted: {encrypted}")
The code adds the shift value directly to each character's code. This pushes characters like 'z' beyond the alphabet, resulting in unintended symbols instead of wrapping back to 'a'. The corrected approach below prevents this overflow.
message = "z{|}"
shift = 5
encrypted = ""
for char in message:
shifted_value = ((ord(char) - 32 + shift) % 95) + 32
encrypted += chr(shifted_value)
print(f"Original: {message}\nEncrypted: {encrypted}")
The fix uses the modulo operator (%) to keep the shifted character within the printable ASCII range. It works by normalizing the value, applying the shift, and then using the modulo operator % 95 to wrap it back around if it goes past the last character. Adding 32 back restores the correct ASCII code.
- This prevents letters from turning into unintended symbols.
- Keep this in mind when building ciphers or cycling through character sets.
Real-world applications
Beyond basic conversions and error handling, these functions let you build practical applications like a simple Caesar cipher or a URL encoding utility.
Creating a simple Caesar cipher with ord() and chr()
The Caesar cipher is a simple encryption method that shifts letters, which you can build by combining ord(), chr(), and modular arithmetic to wrap the alphabet correctly.
message = "HELLO"
shift = 3
encrypted = ""
for char in message:
ascii_value = ord(char)
shifted_value = (ascii_value - 65 + shift) % 26 + 65
encrypted += chr(shifted_value)
print(f"Original: {message}\nEncrypted: {encrypted}")
This code encrypts the message by shifting each letter three places forward. It iterates through the string, using ord() to get each character's ASCII value. The core logic is in the expression (ascii_value - 65 + shift) % 26 + 65.
- Subtracting 65 normalizes the character to a 0-25 range, making the math simpler.
- The modulo operator (
%) ensures the shift wraps around the alphabet, so 'Z' correctly becomes 'C'. - Adding 65 back converts the number to the proper ASCII code for an uppercase letter before
chr()creates the final character.
Implementing URL encoding with ASCII values
To make text safe for web addresses, you can implement URL encoding, which uses ord() to replace special characters with a % followed by their hexadecimal ASCII value.
url_text = "Hello World! @"
encoded = ""
for char in url_text:
if char.isalnum():
encoded += char
else:
encoded += f"%{ord(char):02X}"
print(f"Original: {url_text}\nEncoded: {encoded}")
This code processes a string to make it compatible with systems that only accept a limited character set, an important aspect of securing code. It loops through each character, using the isalnum() method to decide its path.
- If a character is a letter or number, it's added to the
encodedstring unchanged. - If it's a special character—like a space or
!—it's converted. Theord()function finds its integer code, which is then formatted into a two-digit hexadecimal value prefixed with a%using an f-string.
Get started with Replit
Turn your knowledge of ord() and chr() into a real application. Just tell Replit Agent: "Build a text-to-ASCII converter with binary and hex outputs" or "Create a simple Caesar cipher tool".
The Agent writes the code, tests for errors, and deploys the app for you. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



