Python Common tools small function-character type conversion

Source: Internet
Author: User

There are two types of Python3 that represent the sequence of characters: bytes and str. An instance of the former contains bytes with the original 8-bit value, 8 bits per byte, and an instance of the latter containing Unicode characters. The most common encoding for turning Unicode characters into binary data is UTF-8, which must use the Encode method; The Decode method must be used to turn binary data into Unicode characters.

In actual development we often need to convert between these two character types, so we need to write two auxiliary functions to convert between these two situations, so that the converted input data can meet our expectations.

1, accept Str or bytes, and always return str method:

def to_str (str_or_bytes):

If Isinstance (str_or_bytes,bytes):

Value = Str_or_bytes.decode (' Utf-8 ')

Else

Value = Str_or_bytes

return value

2, accept Str or bytes, and always return the method of bytes:

def to_bytes (str_or_bytes):

If Isinstance (STR_OR_BYTES,STR):

Value = Str_or_bytes.encode (' Utf-8 ')

Else

Value = Str_or_bytes

return value

Python Common tools small function-character type conversion

Related Article

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.