Python uses UTF-8 encoding)

Source: Internet
Author: User

Source: http://blog.chenlb.com/2010/01/python-use-utf-8.html

Generally, I like to use UTF-8 encoding. How can I use it in Python?

1. Use UTF-8 In the Python source code file. Generally, an error is reported as follows:

File "F: \ workspace \ PSH \ SRC \ test. py", line 2
Syntaxerror: Non-ASCII character '\ xe4' in file F: \ workspace \ PSH \ SRC \ test. py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

Test. py content:

    1. Print "Hello"

If you want to run normally, add an encoding comment before the test. py file, for example:

  1. #! /Usr/bin/python2.6
  2. #-*-Coding: UTF-8 -*-
  3. Print "Hello"

2,
How does Python do the URL encode UTF-8?

How does one convert Windows command line parameters to UTF-8?

Code:

  1. #-*-Coding: UTF-8 -*-
  2. ImportUrllib
  3. ImportSys
  4. If _ name _ = '_ main _' :
  5. IfLen (SYS. argv)>1:
  6. STR = SYS. argv [1]
  7. STR = Unicode (STR,'Gbk')
  8. Else:
  9. STR ="Chinese"
  10. PrintStr
  11. Params = {}
  12. Params ['Name'] = Str. encode (UTF-8")
  13. PrintUrllib. urlencode (Params)

In python, Unicode is used internally.

Since Windows command lines are encoded in GBK format, you can convert them to Unicode (the third eight rows ).

To convert the URL to encode, convert STR to UTF-8.

Default output result:

Chinese
Name = % E4 % B8 % ad % E6 % 96% 87

It is easy to write a Python script for small tasks. For example, to obtain SOLR data, the solr url encoding is UTF-8.

Reference: http://evanjones.ca/python-utf8.html

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.