How to print the ASCII value in Python
Learn how to print ASCII values in Python. Discover different methods, tips, real-world applications, and how to debug common errors.

Python offers a simple way to get the ASCII value of any character. This is a key skill for tasks like data validation or text manipulation. The built-in ord() function handles this directly.
Here, you'll explore techniques to print ASCII values with practical examples. You'll also find real-world applications, implementation tips, and advice to debug common errors you might encounter.
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 the key to this operation. It takes a single character, like 'A', and returns its integer representation based on the ASCII standard. In this case, the function correctly identifies 65 as the numerical value for the uppercase letter A.
This simple conversion is fundamental for any character-based logic. It's what allows you to perform mathematical operations or comparisons on characters by first translating them into a universal numerical format.
Basic ASCII conversion techniques
Beyond single characters, you can process entire strings into ASCII values, convert them back with chr(), and even manage characters within specific numerical 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]
A list comprehension is a concise way to convert an entire string. This technique iterates through each character, applying the ord() function to each one. This approach effectively breaks the string down into its numerical parts:
- It processes one character at a time from the input string.
- The
ord()function finds the integer value for that character. - All resulting integers are collected into a new list.
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 corresponding character. This example uses a generator expression to efficiently process a list of ASCII values, converting each number into its character form.
- The
chr()function translates each integer, like65, into its character equivalent,'A'. - Then, the
''.join()method assembles these individual characters into a single, coherent 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 also work with specific character sets by using their known ASCII numerical ranges. The code iterates from 65 to 90, which represents the uppercase alphabet in the ASCII standard.
- Inside the loop,
chr()converts each number back into a character. - The
print()function then displays the character alongside its original ASCII value. - Using
end=" "ensures all output appears on a single line, separated by spaces instead of line breaks.
This method is useful for generating character maps or validating input against a specific set like letters or numbers.
Advanced ASCII manipulation techniques
Building on basic conversions, you can also create structured ASCII maps, generate binary representations, and handle hexadecimal values for more complex data handling tasks.
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 offers a compact way to create a character-to-ASCII map. This one-liner iterates through the string, pairing each character with its numerical value from the ord() function.
- The expression
{char: ord(char)}defines the key-value structure for each item. - The loop
for char in textsupplies the characters to be processed.
This method builds an efficient lookup table. It's useful when you need to quickly access a character's ASCII value multiple times without calling ord() repeatedly.
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 code generates a formatted table showing ASCII values alongside their character and 8-bit binary representations. It focuses on the range from 33 to 47, which covers common symbols. The process combines several functions to achieve the clean, aligned output.
- The
bin()function first converts each number to a binary string, which starts with a'0b'prefix. - Slicing with
[2:]neatly removes that prefix. - Then,
zfill(8)pads the string with leading zeros to create a standard 8-bit format, making the binary values uniform and easy to read.
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 handle hexadecimal values by combining familiar functions. The code first converts each character into its hexadecimal ASCII representation using a list comprehension. It’s a two-step move: ord() gets the integer, and then hex() formats it as a hex string like '0x41'.
Reversing the operation is just as straightforward.
- Each hex string is converted back to an integer with
int(h, 16), where the16tells Python it's a base-16 number. chr()turns the integer back into a character, and''.join()stitches the string together again.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the ASCII manipulation techniques we've explored, Replit Agent can turn them into production-ready tools.
- Build an interactive ASCII converter that instantly displays decimal, hex, and binary values for any character input.
- Create a simple text encryption tool that shifts character codes to hide messages.
- Deploy a data sanitization utility that validates user input by checking for characters within an allowed ASCII range.
Describe your app idea, and the agent writes the code, tests it, and fixes issues automatically, all in your browser. Try Replit Agent to bring your concepts to life.
Common errors and challenges
When working with ASCII values in Python, you might run into a few predictable issues, but they're all straightforward to solve.
Handling non-ASCII characters with ord()
The ord() function is designed for single characters. If you pass it a string containing more than one, Python raises a TypeError. It's also important to remember that while ord() handles any Unicode character, values for non-ASCII characters like 'é' or '€' fall outside the standard 0–127 range, which can disrupt logic that expects pure ASCII.
Fixing incorrect ASCII to character conversion with chr()
The chr() function has its limits. It only accepts integers that map to valid Unicode code points, so providing a number outside the range of 0 to 1,114,111 will trigger a ValueError. This error often occurs when arithmetic operations on character codes produce a negative or an excessively large number.
Preventing overflow errors in ASCII arithmetic operations
When you perform math on ASCII values, it's easy to "overflow" the intended character set. For instance, shifting the value of 'Z' (90) by 5 results in 95, which corresponds to the underscore character _ instead of wrapping back to 'E'. This can produce unexpected characters or even a ValueError if the result is out of bounds.
To manage this, you can use the modulo operator (%). It helps keep your results within a specific range by wrapping the values around, which is perfect for tasks like implementing a simple cipher where 'Z' should be followed by 'A'.
Handling non-ASCII characters with ord()
The ord() function can process any Unicode character, but its output for non-ASCII characters like 'é' will exceed the standard 0–127 range. This can cause issues in systems designed only for ASCII. A simple check can prevent unexpected behavior.
The following example shows how to catch these characters by checking if their ord() value exceeds 127, raising a ValueError when one is found.
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 try block identifies the 'é' character as non-ASCII since its value exceeds 127, which then raises the ValueError. The code below demonstrates how you can process such strings without raising an error.
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")
Instead of raising an error, this solution filters out problematic characters. It uses a list comprehension with ord(char) > 127 to find any non-ASCII characters in a string. A second comprehension then builds a new, sanitized string containing only characters within the standard ASCII range. This is a practical way to clean user input or prepare text for systems that don't support extended character sets, preventing unexpected behavior.
Fixing incorrect ASCII to character conversion with chr()
The chr() function is straightforward, but it can fail if you don't give it clean integer inputs. A common mistake is trying to convert a string of space-separated numbers without splitting it first, which causes int() to raise a ValueError.
The following code demonstrates what happens when you try to iterate over the string directly.
values = "65 66 67 68"
text = ''.join(chr(int(value)) for value in values)
print(f"Converted text: {text}")
The loop processes the string character by character, so int() tries to convert the space between numbers. This fails because a space isn't an integer. The corrected approach below shows how to parse the string properly.
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 split() method, which turns the single string of numbers into a list. This ensures that int() receives clean, individual number strings like '65' instead of single characters or spaces. It's a simple but crucial step to avoid a ValueError whenever you're parsing numerical data that's been formatted as a single, space-delimited string. The loop can then correctly convert each number to its character equivalent.
Preventing overflow errors in ASCII arithmetic operations
When you perform math on ASCII values, it's easy to go past the intended character set. Adding a number to 'z', for instance, can produce a symbol instead of wrapping back to the start of the alphabet. This is an overflow error.
The following code shows what happens when a simple character shift pushes values outside their expected range, resulting in garbled output.
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 operation ord(char) + shift blindly adds 5 to each character's value. This pushes characters like z and { beyond their intended range, resulting in non-alphabetic symbols. The corrected approach below prevents this from happening.
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}")
This solution uses the modulo operator (%) to keep shifted values within the printable ASCII range. It's a reliable way to prevent overflow when your logic—like a Caesar cipher—requires character values to wrap around instead of exceeding their boundary.
- The expression
(ord(char) - 32 + shift)calculates the new position. - Using
% 95ensures the result wraps within the 95 printable characters. - Adding
32back maps it to the correct ASCII code.
Real-world applications
Mastering ord() and chr() unlocks practical applications, from building simple ciphers to implementing web-safe URL encoding.
Creating a simple Caesar cipher with ord() and chr()
The ord() and chr() functions, combined with the modulo % operator, provide everything you need to implement a Caesar cipher that encrypts a message by shifting its letters.
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 forward. It’s a classic Caesar cipher that relies on a clever mathematical trick to handle alphabet wrapping. The core logic is in the expression (ascii_value - 65 + shift) % 26 + 65.
- First, it normalizes each character's ASCII value to a 0-25 range by subtracting 65, the value of 'A'.
- After adding the
shift, the modulo operator (% 26) ensures the result wraps around the 26-letter alphabet. - Finally, adding 65 back converts the result into the correct ASCII code for the new letter, which
chr()then turns back into a character.
Implementing URL encoding with ASCII values
URL encoding relies on ASCII values to make text safe for web addresses, converting any non-alphanumeric character into its percent-prefixed hexadecimal equivalent.
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 manually builds a URL-encoded string. It loops through each character, using the isalnum() method to check if it's a letter or number. Safe characters are kept as is, while special characters are converted using a three-step process.
- The
ord()function first gets the character's integer ASCII value. - An f-string with the format specifier
:02Xturns this value into a two-digit, uppercase hexadecimal number. - Finally, a
%symbol is prepended to complete the percent-encoding format.
The result is a new string where all special characters are correctly escaped.
Get started with Replit
Turn your knowledge of ord() and chr() into a real tool. Tell Replit Agent to "build a web app that converts text to its ASCII, hex, and binary values" or "create a simple text encryption tool."
The agent writes the code, tests for errors, and deploys your app right from your browser. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.



%2520in%2520Python.png)