性无码一区二区三区在线观看,少妇被爽到高潮在线观看,午夜精品一区二区三区,无码中文字幕人妻在线一区二区三区,无码精品国产一区二区三区免费

python字符串、列表和bytes的相互轉(zhuǎn)換 日常積累

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
聲明:本內(nèi)容為作者獨(dú)立觀點(diǎn),不代表電子星球立場(chǎng)。未經(jīng)允許不得轉(zhuǎn)載。授權(quán)事宜與稿件投訴,請(qǐng)聯(lián)系:editor@netbroad.com
覺得內(nèi)容不錯(cuò)的朋友,別忘了一鍵三連哦!
贊 2
收藏 2
關(guān)注 19
成為作者 賺取收益
全部留言
0/200
成為第一個(gè)和作者交流的人吧