3

Recently I've been studying Python, there is some differences between Py2 and Py3, and it's hard to understand them for new babies.

The shebang in the head is

#!/usr/bin/env python
#-*- coding:utf-8 -*-

And when I want to print out the Chinese characters, things don't work out.

why they appear as the 'utf-8' format, not the original ones even if I add the ".decode()" function in each sentence, they are just the same.

the right way to show the characters

When it comes to Python3, I got an error msg.

UnicodeEncodeError: 'ascii' codec can't encode characters in position 2-3: ordinal not in range(128)
[Finished in 0.1s with exit code 1]
falsetru
  • 357,413
  • 63
  • 732
  • 636
Ethan
  • 53
  • 2
  • 10
  • 1
    it seems your console/terminal/cmd.exe/powershell doesn't use `UTF-8` so Python can't convert it to `UTF-8` and it uses `ascii` which doesn't have China chars. – furas Jan 23 '17 at 13:37
  • to print text you have to use `encode()` (or `encode('utf-8')`), not `decode()`. `decode()` is used to convert ie. `UTF-8` to `UNICODE` when you get text from keyboard, or from network/socket/file. `encode()` is used to convert `UNICODE` to `UTF-8` when you what to print or send by network/socket or save in file. – furas Jan 23 '17 at 13:39
  • BTW: if you print list then Python uses `repr(...)` with every element on list to show you information usefull for debuging - ie. `u"\u7532"`. You have to concatenate elements from list to one string before you print it - ie. `print("".join(jiazi]))` – furas Jan 23 '17 at 13:44
  • What doesn't work? – Alastair McCormack Jan 24 '17 at 09:05

0 Answers0