1、字符串轉(zhuǎn)bytes
方式一:
''' string to bytes eg:
'0123456789ABCDEF0123456789ABCDEF' b'0123456789ABCDEF0123456789ABCDEF' '''
def stringTobytes(str):
return bytes(str,encoding='utf8')
方式二:
def stringTobytes(str):
b=str.encode('utf-8')
print(b)
2、bytes轉(zhuǎn)字符串
# bytes轉(zhuǎn)字符串方式一
''' bytes to string eg:
b'0123456789ABCDEF0123456789ABCDEF'
'0123456789ABCDEF0123456789ABCDEF' '''
def bytesToString(bs):
return bytes.decode(bs,encoding='utf8')
# bytes轉(zhuǎn)字符串方式二
b=b'\xe9\x80\x86\xe7\x81\xab'
string=str(b,'utf-8')
print(string)
# bytes轉(zhuǎn)字符串方式三
b=b'\xe9\x80\x86\xe7\x81\xab'
string=b.decode() # 第一參數(shù)默認(rèn)utf8,第二參數(shù)默認(rèn)strict
print(string)
# bytes轉(zhuǎn)字符串方式四
b=b'\xe9\x80\x86\xe7\x81haha\xab'
string=b.decode('utf-8','ignore') # 忽略非法字符,用strict會(huì)拋出異常
print(string)
# bytes轉(zhuǎn)字符串方式五
b=b'\xe9\x80\x86\xe7\x81haha\xab'
string=b.decode('utf-8','replace') # 用?取代非法字符
print(string)
3、十六進(jìn)制字符串轉(zhuǎn)bytes
''' hex string to bytes eg:
'01 23 45 67 89 AB CD EF 01 23 45 67 89 AB CD EF'
b'\x01#Eg\x89\xab\xcd\xef\x01#Eg\x89\xab\xcd\xef' '''
def hexStringTobytes(str):
str = str.replace(" ", "")
return bytes.fromhex(str)
# return a2b_hex(str)
4、bytes轉(zhuǎn)十六進(jìn)制字符串
'''
bytes to hex string
eg:
b'\x01#Eg\x89\xab\xcd\xef\x01#Eg\x89\xab\xcd\xef'
'01 23 45 67 89 AB CD EF 01 23 45 67 89 AB CD EF'
'''
def bytesToHexString(bs):
# hex_str = ''
# for item in bs:
# hex_str += str(hex(item))[2:].zfill(2).upper() + " "
# return hex_str
return ''.join(['%02X ' % b for b in bs])
5.字符串轉(zhuǎn)列表
str1 = "hi hello world"
print(str1.split(" ")) 輸出: ['hi', 'hello', 'world']
6.列表轉(zhuǎn)字符串
l = ["hi","hello","world"]
print(" ".join(l)) 輸出: hi hello world
7.十進(jìn)制和十六進(jìn)制相互轉(zhuǎn)換
7.1十進(jìn)制 、十六進(jìn)制轉(zhuǎn)換
10進(jìn)制轉(zhuǎn)16進(jìn)制: hex(16) ==> 0x10
16進(jìn)制轉(zhuǎn)10進(jìn)制: int('0x10', 16) ==> 16
類似的還有oct(), bin()
7.2 字符串轉(zhuǎn)整數(shù):
10進(jìn)制字符串: int('10') ==> 10
16進(jìn)制字符串: int('10', 16) ==> 16
16進(jìn)制字符串: int('0x10', 16) ==> 16