Python small function character type conversion method

高洛峰
Release: 2017-03-21 13:37:10
Original
1617 people have browsed it

Python3 has two types representing character sequences: bytes and str. Instances of the former contain raw 8-bit values ​​of bytes, each of which has 8 binary bits; instances of the latter contain Unicode characters. The most common encoding method to convert Unicode characters into binary data is UTF-8, and the encode method must be used; to convert binary data into Unicode characters, the decode method must be used.

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. Method that accepts str or bytes and always returns str:

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. 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

 

The above is the detailed content of Python small function character type conversion method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!