Home > Backend Development > Python Tutorial > Python common type conversion implementation

Python common type conversion implementation

Guanhui
Release: 2020-07-28 18:22:14
forward
2878 people have browsed it

Python common type conversion implementation

##1. Convert byte and str to each other

b = b"example" 
s = "example" 
bytes(s, encoding = "utf8") 
str(b, encoding = "utf-8")
Copy after login


2. Conversion between byte and int

b=b'\x01\x02'
num=int.from_bytes(b,'little')
b1=num.to_bytes(2,'little')
Copy after login


##3. Conversion between byte and float

import struct
s=b'@zQ\x16'
def byteToFloat(b):
  return struct.unpack('!f',s)[0]

def floatToBytes(f):
  bs = struct.pack("f",f)
  return bytes((bs[3],bs[2],bs[1],bs[0]))
f1=byteToFloat(s)
floatToBytes(f1)
Copy after login

4. Conversion between str and bytearray

str1='aaabb'
ba=bytearray(str1,encoding='utf-8')
str2=ba.decode('utf8')
Copy after login
Recommended tutorial: "

Python Tutorial

"

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

Related labels:
source:jb51.net
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