如何向bytearray追加值?代码无报错但未得预期结果求助
Hey there! Let's clear up the confusion here—your code did successfully append the value 13 to the bytearray. The issue is just how Python chooses to display bytearray objects in the console.
What's Going On with the Display?
When you print or inspect a bytearray, Python will show:
- Printable ASCII characters as their actual character (e.g., 36 =
$, 48 =0) - Non-printable control characters (like 12, 23, 13) as hex escape sequences or special escape codes.
In your case:
- 13 corresponds to the ASCII carriage return character, which Python displays as
\r - 12 is
\x0c(form feed), 23 is\x17(device control 1) — these are non-printable, so hex escapes are used - 36 (
$) and 48 (0) are printable, so they show up as-is
How to Confirm the Value Is Actually There
To see the raw decimal values in the bytearray, convert it to a list:
x = [12,23,36,48] z = bytearray(x) z.append(13) print(list(z)) # Output: [12, 23, 36, 48, 13]
If you prefer to view all values as hexadecimal, you can use the binascii module:
import binascii print(binascii.hexlify(z)) # Output: b'0c1724300d'
Here, 0d is the hexadecimal representation of 13, confirming it's present.
Key Takeaway
Your append(13) call worked perfectly—Python just uses a compact display format for bytearrays that prioritizes readable characters when possible. If you need to verify the actual numeric values, converting to a list or using hex formatting will show you exactly what's stored.
内容的提问来源于stack exchange,提问作者Ankur Singh

