Python 3中打印单字节\xd0为何输出\xc3\x90?
print("\xd0", end="") output c3 90 instead of \xd0 in Python 3.7.2? Great question—this boils down to two core Python 3 behaviors that are easy to mix up: how string literals work, and how print() handles output encoding. Let's break it down step by step:
1. "\xd0" is a Unicode character, not a raw byte
In Python 3, string literals ("" or '') represent Unicode strings, not sequences of raw bytes. When you write "\xd0", Python interprets the \x escape as a Unicode code point in the Latin-1 range (0x00 to 0xFF). Specifically, \xd0 maps to the Unicode character U+00D0 (LATIN CAPITAL LETTER ETH, Ð).
2. print() encodes Unicode strings to your system's default encoding
The print() function doesn't write strings directly to stdout—it first encodes the Unicode string to a byte sequence using the default encoding of sys.stdout (almost always UTF-8 on modern systems).
The Unicode character U+00D0 has a UTF-8 encoding of c3 90—that's exactly the byte sequence you're seeing when you pipe to xxd.
How to output the raw byte \xd0
If you want to write the single byte 0xd0 to stdout (bypassing Unicode encoding), you need to work with a bytes object instead of a string, and write directly to the stdout buffer:
import sys sys.stdout.buffer.write(b"\xd0")
Test this with your command line:
$ python -c 'import sys; sys.stdout.buffer.write(b"\xd0")' | xxd
You'll get the expected output:
00000000: d0
The b"\xd0" syntax creates a bytes object containing the raw byte 0xd0, and writing it to sys.stdout.buffer skips the Unicode encoding step that print() performs.
Quick Cheat Sheet
"\xd0": Unicode characterU+00D0(Ð) → encoded to UTF-8 asc3 90b"\xd0": Raw byte0xd0→ written directly to stdout asd0
内容的提问来源于stack exchange,提问作者Aaron Esau

