Python encoded records

Source: Internet
Author: User

byte Stream and string

When you use Python to define a string, you actually store a byte string:

" ABC [--[97][98][99]

python2.x defaults to treat all strings as ASCII, but when the byte value is >127, the default parsing is problematic.

x="ABC"+chr (page)print  repr (x)#' abc\x96 ' u"Hello" + x#unicodedecodeerror: ' ASCII ' codec Can ' t decode byte

This requires that we get a byte stream and call it a decoding method to create a string (Unicode object)

x="abc\x80\x93"x=x.decode ("Utf-8")Printtype (x)<type'Unicode'>y="ABC"+char (150) y=y.decode ("windows-1252")Printtype (y)<type'Unicode'>Printx+y#abc-abc-

Codecs module

can provide a lot of help when processing the byte stream. You can use the defined encoding to open the file and the content that you read from the file is automatically converted to a Unicode object, or you can process the Unicode object with the specified encoding and then write to the file.

Import codecsf=codecs.open ('0.txt'w' ) Utf-8') f.write (u"\u2013") f.close ()

Reference: HTTP://WWW.TUICOOL.COM/ARTICLES/2MVRVV7

Python encoded records

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.