1、字符串转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转字符串
# bytes转字符串方式一
''' bytes to string eg:
b'0123456789ABCDEF0123456789ABCDEF'
'0123456789ABCDEF0123456789ABCDEF' '''
def bytesToString(bs):
return bytes.decode(bs,encoding='utf8')
# bytes转字符串方式二
b=b'\xe9\x80\x86\xe7\x81\xab'
string=str(b,'utf-8')
print(string)
# bytes转字符串方式三
b=b'\xe9\x80\x86\xe7\x81\xab'
string=b.decode() # 第一参数默认utf8,第二参数默认strict
print(string)
# bytes转字符串方式四
b=b'\xe9\x80\x86\xe7\x81haha\xab'
string=b.decode('utf-8','ignore') # 忽略非法字符,用strict会抛出异常
print(string)
# bytes转字符串方式五
b=b'\xe9\x80\x86\xe7\x81haha\xab'
string=b.decode('utf-8','replace') # 用?取代非法字符
print(string)
3、十六进制字符串转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转十六进制字符串
'''
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.字符串转列表
str1 = "hi hello world"
print(str1.split(" ")) 输出: ['hi', 'hello', 'world']
6.列表转字符串
l = ["hi","hello","world"]
print(" ".join(l)) 输出: hi hello world
7.十进制和十六进制相互转换
7.1十进制 、十六进制转换
10进制转16进制: hex(16) ==> 0x10
16进制转10进制: int('0x10', 16) ==> 16
类似的还有oct(), bin()
7.2 字符串转整数:
10进制字符串: int('10') ==> 10
16进制字符串: int('10', 16) ==> 16
16进制字符串: int('0x10', 16) ==> 16