Table of contents
Implement code functionality

How to print the ASCII value in Python

May 30, 2025
 ・ by  
the Anthropic Team
Table of contents
H2 Link Template
Try Claude

ASCII values represent characters as numeric codes in Python, enabling text processing and character manipulation. The Python standard library provides built-in functions like ord() and chr() to convert between characters and their ASCII equivalents.

This guide covers essential techniques for printing ASCII values, with practical examples and troubleshooting tips. All code examples were developed with Claude, an AI assistant built by Anthropic.

Using the ord() function to get ASCII values

character = 'A'
ascii_value = ord(character)
print(f"The ASCII value of '{character}' is {ascii_value}")
The ASCII value of 'A' is 65

The ord() function converts a single character into its corresponding ASCII decimal value. In the example, it transforms the character 'A' into 65, which represents its position in the ASCII character encoding scheme.

This conversion serves several practical purposes in text processing:

  • Performing character-based calculations and comparisons
  • Implementing custom text encoding algorithms
  • Validating input strings based on ASCII ranges
  • Converting between different character representations

The f-string output demonstrates a common pattern for debugging and educational purposes. It displays both the original character and its ASCII value, helping developers understand the relationship between text and its numeric representation.

Basic ASCII conversion techniques

Building on the ord() function's capabilities, Python offers several essential techniques for converting between strings and ASCII values, enabling flexible text manipulation across different character 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}")
ASCII values of 'Hello': [72, 101, 108, 108, 111]

This code demonstrates a list comprehension that transforms each character in a string into its ASCII value. The [ord(char) for char in text] syntax creates a new list by applying the ord() function to every character in the input string.

  • The string "Hello" gets processed character by character
  • Each letter converts to its corresponding ASCII decimal number
  • The resulting list contains five integers representing H, e, l, l, o

This technique proves particularly useful when you need to analyze text patterns or implement character-based algorithms. The f-string output provides a clear view of how the original text maps to its numeric ASCII representation.

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}")
ASCII values [65, 66, 67, 68] converted to text: ABCD

The chr() function reverses ASCII conversion by transforming numeric values back into characters. This example demonstrates how to convert a list of ASCII values into their corresponding text representation.

  • The chr(value) generator expression processes each number in the list
  • Python's join() method combines the resulting characters into a single string
  • The empty string '' serves as the separator between joined characters

This technique proves invaluable when working with data that stores text as numeric ASCII values. The output shows how [65, 66, 67, 68] transforms into "ABCD", making it easier to display or process text-based information in a human-readable format.

Working with ASCII ranges

# Print uppercase letters and their ASCII values
for value in range(65, 91):
    print(f"{chr(value)}: {value}", end="  ")
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

The code demonstrates how to systematically print all uppercase letters alongside their ASCII values. The range(65, 91) function generates numbers from 65 (ASCII for 'A') to 90 (ASCII for 'Z'), creating a sequence that maps to the uppercase alphabet.

  • The chr(value) function converts each number back to its letter representation
  • The f-string formats each pair of letter and ASCII value together
  • Setting end=" " in the print statement creates a space-separated output instead of new lines

This pattern proves particularly useful when you need to work with specific character ranges or implement character validation. Understanding these ASCII ranges helps you process text data more effectively in your applications.

Advanced ASCII manipulation techniques

Building on the foundational ASCII techniques, Python offers powerful ways to map, visualize, and convert ASCII values through dictionary comprehensions, binary representations, and hexadecimal transformations.

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)
{'P': 80, 'y': 121, 't': 116, 'h': 104, 'o': 111, 'n': 110}

Dictionary comprehensions create a mapping between characters and their ASCII values in a single, readable line. The {char: ord(char) for char in text} syntax generates key-value pairs where each character becomes a key linked to its ASCII equivalent.

  • Each character in "Python" serves as a dictionary key
  • The ord() function converts each character to its ASCII value
  • The resulting dictionary makes character-to-ASCII lookups efficient

This technique proves particularly useful when you need to analyze character frequencies or implement custom character encoding schemes. The dictionary structure provides instant access to ASCII values without repeatedly calling ord() on the same characters.

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}")
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 ASCII table displaying characters between ASCII values 33 and 47. The range(33, 48) function creates a sequence of numbers representing printable ASCII symbols like !, @, and #.

  • The chr(i) function converts each number to its corresponding character
  • The bin(i)[2:] converts the ASCII value to binary. The [2:] slice removes the "0b" prefix
  • The zfill(8) method pads the binary number with leading zeros to ensure 8-bit representation
  • The f-string formats each row with aligned columns using {i:3d} for decimal numbers and {char:^3} for centered characters

This visualization helps developers understand the relationship between decimal ASCII values, their character representations, and underlying binary patterns. The table format makes it easy to spot patterns in the binary progression.

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)}")
Hexadecimal ASCII values of 'ASCII': ['0x41', '0x53', '0x43', '0x49', '0x49']
Back to text: ASCII

The code demonstrates bidirectional conversion between ASCII characters and their hexadecimal representations. The list comprehension [hex(ord(char))] first converts each character to its ASCII value using ord(), then transforms it to hexadecimal using hex().

  • The hex() function adds a '0x' prefix to indicate hexadecimal notation
  • Converting back to text requires two steps: int(h, 16) transforms hex to decimal. chr() then converts the decimal to a character
  • The empty string '' joins the converted characters into the final text

This technique proves valuable when working with systems that represent text in hexadecimal format. Common applications include debugging binary data or implementing custom encoding schemes.

Get unstuck faster with Claude

Claude is an AI assistant created by Anthropic that excels at helping developers write, debug, and understand code. Working alongside you, it provides clear explanations and practical solutions for your programming challenges.

As your AI code mentor, Claude helps you navigate complex ASCII manipulations, dictionary comprehensions, and other Python concepts. It can explain tricky syntax, suggest code improvements, or help you understand why your code isn't working as expected.

Start accelerating your Python development today. Sign up for free at Claude.ai and experience the benefits of having an AI assistant guide you through your coding journey.

Some real-world applications

Building on our ASCII manipulation techniques, we'll explore two practical applications that demonstrate how developers use ord() and chr() functions to implement text encryption and URL encoding.

Creating a simple Caesar cipher with ord() and chr()

The Caesar cipher shifts each letter in a message by a fixed number of positions in the alphabet, demonstrating how ord() and chr() functions enable basic text encryption through ASCII value manipulation.

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 transforms text by shifting each letter forward in the alphabet by a specified number of positions. The ord() function converts each character to its ASCII value. Since uppercase letters start at ASCII value 65 ('A'), the code subtracts 65 to work with values 0-25 instead.

  • The modulo operator % 26 ensures the shift wraps around the alphabet
  • Adding 65 back converts the number to the correct ASCII value
  • The chr() function transforms the shifted ASCII value back into a character

For example, with a shift of 3, 'A' becomes 'D', 'B' becomes 'E', and 'Z' wraps around to 'C'. The f-string displays both the original and encrypted messages.

Implementing URL encoding with ASCII values

URL encoding transforms special characters into percent-encoded ASCII values, enabling safe transmission of text data across web protocols by converting spaces, symbols, and non-alphanumeric characters into their hexadecimal representations.

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 implements a basic URL encoder that processes text character by character. The isalnum() function checks if each character is alphanumeric (a-z, A-Z, 0-9). When it finds a non-alphanumeric character like spaces or symbols, it converts them to their hexadecimal ASCII representation prefixed with "%".

  • The :02X format specifier ensures two-digit uppercase hexadecimal output
  • Regular letters and numbers remain unchanged
  • Special characters transform into their percent-encoded equivalents

For example, running this code converts spaces to "%20" and exclamation marks to "%21". This encoding makes text safe for use in URLs by replacing problematic characters with their ASCII-based alternatives.

Common errors and challenges

Python developers frequently encounter three critical challenges when working with ASCII values: handling Unicode characters, managing character conversion errors, and preventing numeric overflows.

Handling non-ASCII characters with ord()

The ord() function works seamlessly with standard ASCII characters but raises challenges with extended Unicode symbols like accented letters or emojis. When processing text that might contain non-ASCII characters, developers need robust error handling to prevent unexpected crashes.

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 code raises a ValueError when it encounters the 'é' character because its Unicode value exceeds 127, the maximum value for standard ASCII characters. Let's examine the improved code below that handles these extended characters properly.

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")

The improved code identifies non-ASCII characters by checking if their ord() values exceed 127. It stores these characters in a list and creates an ASCII-only version of the text by filtering them out. This approach prevents crashes while preserving as much of the original text as possible.

  • Watch for this issue when processing user input or external data sources
  • Text from web forms, files, or APIs often contains non-ASCII characters
  • Consider using Unicode-aware functions like encode() and decode() for more complex text processing needs

Fixing incorrect ASCII to character conversion with chr()

Converting strings of ASCII values to characters requires careful handling of the input format. The chr() function expects individual integers. When processing space-separated ASCII values as strings, direct conversion attempts will fail. The code below demonstrates this common pitfall.

values = "65 66 67 68"
text = ''.join(chr(int(value)) for value in values)
print(f"Converted text: {text}")

The code fails because values.split() isn't used to separate the ASCII numbers. The for loop processes each character in the string individually, including spaces. This causes Python to attempt converting invalid ASCII values.

The corrected implementation below demonstrates the proper way to handle space-separated ASCII values.

values = "65 66 67 68"
text = ''.join(chr(int(value)) for value in values.split())
print(f"Converted text: {text}")

The split() method separates the space-delimited ASCII values into individual numbers before conversion. Without it, Python would process each character individually, including spaces, leading to invalid ASCII values. The corrected code joins the characters after properly converting each ASCII value.

  • Watch for this when processing ASCII values from files or user input
  • Always validate input format before conversion
  • Consider using error handling to catch potential conversion issues

This pattern appears frequently when working with data from external sources that provide ASCII values as text strings. The solution ensures reliable character conversion while maintaining code readability.

Preventing overflow errors in ASCII arithmetic operations

ASCII arithmetic operations can produce unexpected results when calculations push values beyond valid ASCII ranges. When adding or subtracting from ASCII values, the chr() function may receive numbers outside its acceptable input range of 0-1,114,111. The code below demonstrates this common pitfall with character shifting.

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 fails when shifted_value exceeds the maximum valid ASCII value, producing characters outside the printable range. Let's examine a corrected version that implements proper value checking and wrapping.

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 corrected code prevents overflow errors by constraining shifted ASCII values within the printable character range (32-126). The formula ((ord(char) - 32 + shift) % 95) + 32 ensures characters wrap around this range instead of exceeding valid ASCII values.

  • Subtracting 32 normalizes the range to 0-94
  • The modulo operator % 95 handles wrapping
  • Adding 32 back shifts values to the printable range

Watch for this issue when implementing character shifting operations or text transformations. The error commonly occurs in encryption algorithms, text formatting utilities, and character manipulation functions that modify ASCII values.

Learning or leveling up? Use Claude

Claude combines deep technical expertise with natural conversational abilities to help you master Python concepts and solve coding challenges. As your dedicated programming companion, it breaks down complex topics into clear, actionable explanations while suggesting practical improvements to your code.

  • ASCII Table Reference: Ask "Show me the ASCII values for lowercase letters" and Claude will generate a formatted table mapping characters to their decimal values.
  • Code Debugging: Ask "Why isn't my ASCII conversion working?" with your code snippet and Claude will identify issues, explain the problem, and suggest fixes.
  • Implementation Help: Ask "How do I implement URL encoding using ASCII values?" and Claude will provide a step-by-step solution with explanations.
  • Best Practices: Ask "What's the safest way to handle non-ASCII characters?" and Claude will outline robust approaches for text processing.
  • Code Review: Ask "Review my ASCII manipulation code" and Claude will analyze your implementation, suggesting optimizations and potential improvements.

Ready to accelerate your Python development? Visit Claude.ai to access a powerful AI assistant that helps you write better code faster.

For seamless integration into your development workflow, Claude Code brings AI assistance directly to your terminal—enabling rapid prototyping, debugging, and code optimization without leaving your preferred environment.

FAQs

Additional Resources

How to remove an item from a list in Python

2025-05-30
14 min
 read
Read more

How to add a key value pair to a dictionary in Python

2025-05-30
14 min
 read
Read more

How to remove non-alphanumeric characters in Python

2025-05-30
14 min
 read
Read more

Leading companies build with Claude

ReplitCognitionGithub CopilotCursorSourcegraph
Try Claude
Get API Access
Copy
Expand