杰瑞科技汇

Python中int转char怎么实现?

Of course! In Python, converting an integer to a character is done using the built-in chr() function. The reverse, converting a character to an integer, is done with ord().

Python中int转char怎么实现?-图1
(图片来源网络,侵删)

The Short and Direct Answer

To convert an integer to its corresponding ASCII (or Unicode) character, use the chr() function.

# Convert integer 65 to a character
my_int = 65
my_char = chr(my_int)
print(my_char)
# Output: 'A'

Detailed Explanation

The chr() Function

The chr(i) function takes an integer i (which must be in the range 0 <= i <= 0x10FFFF) and returns a string representing the character corresponding to that Unicode code point.

  • For integers 0-127: These correspond directly to the standard ASCII table.
  • For integers 128 and above: These correspond to characters in the Unicode standard, which includes characters from many languages, symbols, emojis, and more.

Examples:

# Standard ASCII characters
print(chr(65))   # Output: 'A'
print(chr(97))   # Output: 'a'
print(chr(48))   # Output: '0'
print(chr(33))   # Output: '!'
# Non-ASCII Unicode characters
print(chr(8364)) # Output: '€' (Euro sign)
print(chr(128515)) # Output: '😃' (Grinning face emoji)

The Reverse: ord() Function

It's very common to see chr() and ord() used together. ord() does the exact opposite of chr().

Python中int转char怎么实现?-图2
(图片来源网络,侵删)
  • ord(c) takes a single character string c and returns its corresponding Unicode code point as an integer.
# Convert character 'A' to its integer code
my_char = 'A'
my_int = ord(my_char)
print(my_int)
# Output: 65
# They are perfect inverses of each other
print(chr(ord('Z'))) # Output: 'Z'
print(ord(chr(122))) # Output: 122

Common Use Cases

Generating the Alphabet

A classic example is generating all the letters of the alphabet.

# Generate lowercase alphabet
start_code = ord('a')
end_code = ord('z')
# Using a list comprehension
lowercase_alphabet = [chr(i) for i in range(start_code, end_code + 1)]
print(lowercase_alphabet)
# Output: ['a', 'b', 'c', ..., 'z']
# Generate uppercase alphabet
uppercase_alphabet = [chr(i) for i in range(ord('A'), ord('Z') + 1)]
print(uppercase_alphabet)
# Output: ['A', 'B', 'C', ..., 'Z']

Creating a Simple Cipher (Caesar Cipher)

You can use integer arithmetic to shift characters. For example, a Caesar cipher shifts each letter by a fixed number of positions.

def caesar_cipher(text, shift):
    result = ""
    for char in text:
        if char.isalpha(): # Only shift letters
            # Get the base ASCII value ('a' for lowercase, 'A' for uppercase)
            base = ord('a') if char.islower() else ord('A')
            # Shift the character, wrapping around the alphabet
            shifted_code = (ord(char) - base + shift) % 26
            result += chr(base + shifted_code)
        else:
            result += char # Leave non-alphabetic characters as they are
    return result
plain_text = "Hello, World!"
shift = 3
cipher_text = caesar_cipher(plain_text, shift)
print(f"Original:  {plain_text}")
print(f"Encrypted: {cipher_text}")
# Output:
# Original:  Hello, World!
# Encrypted: Khoor, Zruog!

Handling Errors

If you try to use chr() with an integer outside the valid range (0 to 1114111), you will get a ValueError.

# This will cause an error
try:
    invalid_char = chr(1114112) # 0x10FFFF + 1
except ValueError as e:
    print(f"Error: {e}")
# Output: Error: chr() arg not in range(0x110000)
# Negative numbers also cause an error
try:
    invalid_char = chr(-1)
except ValueError as e:
    print(f"Error: {e}")
# Output: Error: chr() arg not in range(0x110000)

Summary

Function Purpose Example Output
chr(i) Converts an integer to a character. chr(65) 'A'
ord(c) Converts a character to an integer. ord('A') 65
Python中int转char怎么实现?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇