How to make python 3 print() utf8

前端 未结 2 1928
名媛妹妹
名媛妹妹 2020-11-28 07:32

How can I make python 3 (3.1) print("Some text") to stdout in UTF-8, or how to output raw bytes?

Test.py



        
2条回答
  •  生来不讨喜
    2020-11-28 07:46

    Clarification:

    TestText = "Test - āĀēĒčČ..šŠūŪžŽ" # this not UTF-8...it is a Unicode string in Python 3.X.
    TestText2 = TestText.encode('utf8') # this is a UTF-8-encoded byte string.
    

    To send UTF-8 to stdout regardless of the console's encoding, use the its buffer interface, which accepts bytes:

    import sys
    sys.stdout.buffer.write(TestText2)
    

提交回复
热议问题