如何使用Python将数字数组转换为字符数组?
Hey there! Converting an array of ASCII numeric values to their corresponding character equivalents is a common task, and it’s pretty straightforward across most programming languages. Let’s break down how to do it using your example input [65,97,98,66] (which should give us [A,a,b,B]) with a few popular languages:
JavaScript
Use the map() method to iterate over each number, paired with String.fromCharCode() to handle the conversion:
const numArray = [65, 97, 98, 66]; const charArray = numArray.map(num => String.fromCharCode(num)); console.log(charArray); // Output: ["A", "a", "b", "B"]
String.fromCharCode() takes one or more ASCII integers and returns the matching string characters, making it perfect for this use case.
Python
Python’s built-in chr() function is made for this exact job. We can use a list comprehension to apply it to every element in the array:
num_array = [65, 97, 98, 66] char_array = [chr(num) for num in num_array] print(char_array) # Output: ['A', 'a', 'b', 'B']
The list comprehension keeps the code concise and readable—no need for verbose loops unless you prefer them!
Java
In Java, we can directly cast integers to char types (since ASCII values align with Java’s char encoding). A simple loop will handle the conversion:
public class AsciiConverter { public static void main(String[] args) { int[] numArray = {65, 97, 98, 66}; char[] charArray = new char[numArray.length]; for (int i = 0; i < numArray.length; i++) { charArray[i] = (char) numArray[i]; } // Print the array in a readable format System.out.println(java.util.Arrays.toString(charArray)); // Output: [A, a, b, B] } }
Just make sure your target character array is the same length as the input numeric array to avoid index errors.
Quick Note
Double-check that all numbers in your input array are valid standard ASCII values (0–127). Values outside this range might produce unexpected characters or symbols depending on the language’s default character encoding.
内容的提问来源于stack exchange,提问作者S. Waleed

