The classic question of Python--Chinese garbled

Source: Internet
Author: User

Expect to be encountered when getting started. I was in Windows under the PYTHON25 with the idle editor run, found that running the script results some Chinese display is garbled, but some are normal. The solution is not to be baffled. First, look at the source file encoding format, is UTF-8. After searching and searching, debugging and debugging, we also changed several compilers, and found that it was worse than idle (may need to be encode set). Finally solved the problem, it took me nearly 5 hours, written here, I hope that people who encounter problems can search here, no longer repeat.
Garbled reason: Because your file is declared as Utf-8, and it should also be the source file saved with Utf-8 encoding. But the local default encoding for Windows is cp936, which is GBK encoding, so the string that prints utf-8 directly in the console is, of course, garbled.
Workaround:

In the console printing place with a transcoding is OK, when printed so write:

print myname.decode ('UTF-8'). Encode ('GBK')

A more general approach would be to:

import sys type = sys.getfilesystemencoding () print myname.decode ('UTF-8'). Encode (type)

The classic question of Python--Chinese garbled

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.