In the py2.7 project with the __future__ module in the Unicode_literals to prepare for compatible py3.x, today encountered a unicodeencodeerror error, followed, found that this small pit is worth noting. What kind of a pit is it? Follow the code to see. By the way, the principle.
1. Unicode_literals Version not introduced
| The code is as follows |
Copy Code |
|
#coding: Utf-8
From datetime import datetime
now = DateTime.Now ()
Print Now.strftime ('%m month%d days%h:%m ') |
This code can perform the output correctly: March 12 21:53
2. Introduction of Unicode_literals
| The code is as follows |
Copy Code |
|
#coding: Utf-8
From __future__ import unicode_literals
From datetime import datetime
now = DateTime.Now ()
Print Now.strftime ('%m month%d days%h:%m ') |
The following error was thrown:
Traceback (most recent call last):
File "unicode_error_demo2.py", line 7, in <module>
Print Now.strftime ('%m month%d days%h:%m ')
Unicodeencodeerror: ' ASCII ' codec can ' t encode character U ' u6708 ' in position-not in range (128)
3. Solution One: Set Run-time encoding to Utf-8
| The code is as follows |
Copy Code |
|
#coding: Utf-8
From __future__ import unicode_literals
Import Sys
From datetime import datetime
Reload (SYS)
Sys.setdefaultencoding (' Utf-8 ')
now = DateTime.Now ()
Print Now.strftime ('%m month%d days%h:%m ') |
Normal execution
4. Solution Two: Use byte string
| code is as follows |
copy code |
|
#coding: Utf-8
from __future__ import unicode_literals
to datetime import datetime
now = DateTime.Now ()
Print Now.strftime (b '%m month%d%h:%m ') # is indicated as the ByteArray string
# or it is also OK
T = ByteArray ('%m month%d%h:%m ', ' utf-8 ')
Print Now.strftime (str (t)) |