参考:https://blog.csdn.net/albertsh/article/details/114465098

源类型 目标类型 方式 结果
int str str(10)、’{0}’.format(10) 10 => ‘10’
int str_hex hex(10) 10 => ‘0xa’
int str_bin bin(10).replace(‘0b’,’’) 10 => ‘1010’
str int int(‘10’) ‘10’ => 10
str_hex int int(‘0xa’, 16) ‘0xa’ => 10
str_bin int int(‘1010’, 2) ‘1010’ => 10
int bytes num.to_bytes(length=4, byteorder=’little’, signed=False) 4665 => b’9\x12\x00\x00’
int bytes struct.pack(“<I”, 4665) 4665 => b’9\x12\x00\x00’
bytes int int.from_bytes(b’9\x12\x00\x00’, byteorder=’little’, signed=False) b’9\x12\x00\x00’ => 4665
bytes int struct.unpack(“<I”, b’9\x12\x00\x00’) b’9\x12\x00\x00’ => 4665
int[] bytes bytes([57, 18, 0, 0]) [57, 18, 0, 0] => b’9\x12\x00\x00’
bytes int[] [x for x in b’9\x12\x00\x00’] b’9\x12\x00\x00’ => [57, 18, 0, 0]
str bytes ‘美好’.encode(‘utf-8’) ‘美好’ => b’\xe7\xbe\x8e\xe5\xa5\xbd’
str bytes bytes(‘美好’, ‘utf-8’) ‘美好’ => b’\xe7\xbe\x8e\xe5\xa5\xbd’
bytes str b’\xe7\xbe\x8e\xe5\xa5\xbd’.decode(‘utf-8’) b’\xe7\xbe\x8e\xe5\xa5\xbd’ => ‘美好’
bytes bytes
(无\x)
binascii.b2a_hex(b’\xe7\xbe\x8eqaq’) b’\xe7\xbe\x8eqaq’ => b’e7be8e716171’
bytes bytes
(有\x)
binascii.a2b_hex(b’e7be8e716171’) b’e7be8e716171’ => b’\xe7\xbe\x8eqaq’
bytes str(hex) b’\xe7\xbe\x8eqaq’.hex() b’\xe7\xbe\x8eqaq’ => ‘e7be8e716171’
str(hex) bytes bytes.fromhex(‘e7be8e716171’) ‘e7be8e716171’ => b’\xe7\xbe\x8eqaq’

int -> str

  1. a = 10 # a: <class 'int'> 10
  2. b = str(a) # b: <class 'str'> '10'
  1. a = 10 # a: <class 'int'> 10
  2. b = '{0}'.format(a) # b: <class 'str'> '10'

int -> hex_str

  1. a = 10 # a: <class 'int'> 10
  2. b = hex(a) # b: <class 'str'> '0xa'

int -> bin_str

  1. a = 10 # a: <class 'int'> 10
  2. b = bin(a) # b: <class 'str'> '0b1010'

str -> int

  1. a = int('10') # a: <class 'int'> 10
  2. a = int('0xa', 16) # a: <class 'int'> 10
  3. a = int('a', 16) # a: <class 'int'> 10
  4. a = int('0b1010', 2) # a: <class 'int'> 10
  5. a = int('1010', 2) # a: <class 'int'> 10
  6. a = int('101', 3) # a: <class 'int'> 10
  7. a = int('20', 5) # a: <class 'int'> 10

str -> list

  1. s = 'hello' # s: <class 'str'> 'hello'
  2. a = list(s) # a: <class 'list'> ['h', 'e', 'l', 'l', 'o']

list -> str

  1. a = ['h', 'e', 'l', 'l', 'o'] # a: <class 'list'> ['h', 'e', 'l', 'l', 'o']
  2. s = ''.join(a) # s: <class 'str'> 'hello'

hex_str -> bytes

  1. a = '23ff' # a: <class 'str'> '23ff'
  2. a = bytes.fromhex(a) # a: <class 'bytes'> b'\x23\xff'
  3. b =

[

](https://blog.csdn.net/albertsh/article/details/114465098)