新聞中心
我們?cè)赑ython中會(huì)遇到很多轉(zhuǎn)換的問(wèn)題,例如需要字符串,而輸入內(nèi)容為二進(jìn)制。碼的是字符串,卻要是字符串。字符串與二進(jìn)制如何相互轉(zhuǎn)換呢?本文向大家介紹Python中字符串與二進(jìn)制相互轉(zhuǎn)換的兩種方法,一個(gè)是簡(jiǎn)單版本,另一個(gè)是依靠bitarray對(duì)象,也是可以輕松轉(zhuǎn)化。內(nèi)容如下:

創(chuàng)新互聯(lián)建站專(zhuān)注為客戶(hù)提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于成都做網(wǎng)站、成都網(wǎng)站建設(shè)、成都外貿(mào)網(wǎng)站建設(shè)、橋東網(wǎng)絡(luò)推廣、小程序開(kāi)發(fā)、橋東網(wǎng)絡(luò)營(yíng)銷(xiāo)、橋東企業(yè)策劃、橋東品牌公關(guān)、搜索引擎seo、人物專(zhuān)訪(fǎng)、企業(yè)宣傳片、企業(yè)代運(yùn)營(yíng)等,從售前售中售后,我們都將竭誠(chéng)為您服務(wù),您的肯定,是我們最大的嘉獎(jiǎng);創(chuàng)新互聯(lián)建站為所有大學(xué)生創(chuàng)業(yè)者提供橋東建站搭建服務(wù),24小時(shí)服務(wù)熱線(xiàn):18980820575,官方網(wǎng)址:www.cdcxhl.com
簡(jiǎn)單版本
def encode(s):
return ' '.join([bin(ord(c)).replace('0b', '') for c in s])
def decode(s):
return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])
>>>encode('hello')
'1101000 1100101 1101100 1101100 1101111'
>>>decode('1101000 1100101 1101100 1101100 1101111')
'hello'
bitarray法
將二進(jìn)制串轉(zhuǎn)化為bitarray對(duì)象,bitarray對(duì)象可以輕松轉(zhuǎn)化為bytes
from bitarray import bitarray
def str2bitarray(s):
ret = bitarray(''.join([bin(int('1' + hex(c)[2:], 16))[3:] for c in s.encode('utf-8')]))
return ret
def bitarray2str(bit):
return bit.tobytes().decode('utf-8')
以上就是Python中字符串與二進(jìn)制相互轉(zhuǎn)換的兩種方法,你學(xué)會(huì)了嗎?大家可以直接套用上面的代碼哦~
名稱(chēng)欄目:創(chuàng)新互聯(lián)Python教程:Python中字符串與二進(jìn)制如何相互轉(zhuǎn)換?
URL鏈接:http://m.fisionsoft.com.cn/article/djceosg.html


咨詢(xún)
建站咨詢(xún)
