Specify the encoding of the unicode string in the Python 2.x print statement

The Python 2.x print statement implicitly converts the `ʻunicodetype to the str type and then outputs the standard output. The encoding for converting to ```unicode-> str is determined by locale.getpreferredencoding ().

Try out

↓ When I try to execute Python from Terminal on Mac.

>>> import locale
>>> locale.getpreferredencoding()
'UTF-8'

>>> print u'Ah ah'
Ah ah

↓ When I try to execute Python from the command prompt of Windows 7.

>>> import locale
>>> locale.getpreferredencoding()
'cp932'

>>> print u'Ah ah'
Ah ah

↓ When I try to execute Python from PyDev Console of Eclipse.

>>> import locale
>>> locale.getpreferredencoding()
'US-ASCII'

>>> print u'Ah ah'
Traceback (most recent call last):
  File "<input>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

Since it was ascii in a special environment, ʻu'Ah'`` will result in a ʻUnicodeEncodeError`` error.

I want you to convert with the specified encoding

If you dare to specify the encoding, you can do it by the following method.

>>> import sys, codecs
>>> sys.stdout = codecs.getwriter('utf-8')(sys.stdout)

>>> print u'Ah ah'
Ah ah

Avoid giving errors

It's very likely that you'll hide the bug ...

_ENC_LOCALE = locale.getpreferredencoding()
sys.stdout = codecs.getwriter(_ENC_LOCALE)(sys.stdout, errors='replace')
sys.stderr = codecs.getwriter(_ENC_LOCALE)(sys.stderr, errors='replace')

Recommended Posts

Specify the encoding of the unicode string in the Python 2.x print statement
Find out the apparent width of a string in python
[Introduction to Python] How to output a character string in a Print statement
Conversion of string <-> date (date, datetime) in Python
Check the behavior of destructor in Python
The result of installing python in Anaconda
The basics of running NoxPlayer in Python
In search of the fastest FizzBuzz in Python
I want to batch convert the result of "string" .split () in Python
[Introduction to Python] Thorough explanation of the character string type used in Python!
Output the number of CPU cores in Python
[Python] Sort the list of pathlib.Path in natural sort
Get the caller of a function in Python
Match the distribution of each group in Python
View the result of geometry processing in Python
Make a copy of the list in Python
Get the X Window System window title in Python
Find the divisor of the value entered in python
Find the solution of the nth-order equation in python
[Python numpy] Dynamically specify the index of the array
The story of reading HSPICE data in Python
[Note] About the role of underscore "_" in Python
About the behavior of Model.get_or_create () of peewee in Python
Solving the equation of motion in Python (odeint)
Output in the form of a python array
json.dumping None in python returns the string null
plot the coordinates of the processing (python) list and specify the number of times in draw ()
I installed Pygame with Python 3.5.1 in the environment of pyenv on OS X
Divides the character string by the specified number of characters. In Ruby and Python.
Get the last element of the array by splitting the string in Python and PHP
Check if the string is a number in python
Download the file while viewing the progress in Python 3.x
Experience the good calculation efficiency of vectorization in Python
Specify the lighting Model of SCN Material in Pythonista
About the matter that the contents of Python print are not visible in docker logs
How to get the number of digits in Python
String manipulation in python
Cut a part of the string using a Python slice
Store Japanese (multibyte character string) in sqlite3 of python
[python] Get the list of classes defined in the module
[Python] Change the text color and background color of a specific keyword in print output
the zen of Python
The story of FileNotFound in Python open () mode ='w'
Learn the design pattern "Chain of Responsibility" in Python
Implement the solution of Riccati algebraic equations in Python
[Golang] Specify an array in the value of map
Get the size (number of elements) of UnionFind in Python
Not being aware of the contents of the data in python
Shift the alphabet string by N characters in Python
Reproduce the execution example of Chapter 4 of Hajipata in Python
Let's use the open data of "Mamebus" in Python
Implemented the algorithm of "Algorithm Picture Book" in Python3 (Heapsort)
[Python] Outputs all combinations of elements in the list
Encoding judgment in Python
[Python] Summary of how to specify the color of the figure
Get the URL of the HTTP redirect destination in Python
A reminder about the implementation of recommendations in Python
Reproduce the execution example of Chapter 5 of Hajipata in Python
To do the equivalent of Ruby's ObjectSpace._id2ref in Python
Check the asymptotic nature of the probability distribution in Python
I tried to summarize the string operations of Python