Common python tools-small functions-character type conversion, common python tools

Source: Internet
Author: User

Common python tools-small functions-character type conversion, common python tools

Python3 has two types of character sequences: bytes and str. The former instance contains the original 8-bit value of the byte, each of which has 8 binary digits; the latter instance contains Unicode characters. The most common encoding method for converting Unicode characters to binary data is the UTF-8, which must use the encode method; the decode method must be used to convert binary data to Unicode characters.

In actual development, we often need to convert the two types of characters. Therefore, we need to write two auxiliary functions to convert the two types of characters, this allows the converted input data to meet our expectations.

1. Accept str or bytes and always return the 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. the method that accepts str or bytes and always returns 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

 

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.