How do I specify the encoding during a print()
statement?
Asked
Active
Viewed 488 times
1 Answers
3
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
print()
calls file.write()
, and file
defaults to sys.stdout
. sys.stdout
is a file object whose write()
method encodes strings according to its encoding property. If you reconfigure that property it'll change how strings are encoded when printed:
sys.stdout.reconfigure(encoding='latin-1')
Alternatively, you could encode the string yourself and then write the bytes to stdout's underlying binary buffer.
sys.stdout.buffer.write("<some text>".encode('latin-1'))
Beware that buffer
is not a public property: "This is not part of the TextIOBase API and may not exist in some implementations."

John Kugelman
- 349,597
- 67
- 533
- 578