首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python 2与3中的binascii解码

python 2与3中的binascii解码
EN

Stack Overflow用户
提问于 2021-07-20 05:40:12
回答 1查看 43关注 0票数 1
代码语言:javascript
复制
python2 test.py

ascii_term_id? "0500"
代码语言:javascript
复制
python3 test.py

ascii_term_id? "b'0500'"

我正在尝试让这个函数在python2和3之间工作。Python3的变量中似乎有无关的数据。

我不完全确定这个binascii.b2a_hex在python版本之间是如何工作的:

代码语言:javascript
复制
    if os.path.isfile(C + 'file.TMP'):
        with open(C + 'file.tmp', 'rb') as eamterms:
            sector = eamterms.read(sector_size)
            while sector:
                if sector_count > 0:
                    sector = sector[4:sector_size]
                    for i in range(0, sector_size, record_size):
                        record = sector[i:record_size + i]
                        #print(str(record))
                        # Terminal ID is the key
                        term_id = record[0:2]
                        # convert it to ascii
                        ascii_term_id = binascii.b2a_hex(term_id)
                        #print(str(ascii_term_id) + " " + str(term_id))
                        # Skip nulls and the store record
                        if sector_count == 283:
                            print('ascii_term_id? "' + str(ascii_term_id) + '"')
                            print('----------------------------')
                            quit()
EN

回答 1

Stack Overflow用户

发布于 2021-07-20 07:25:40

你应该使用

代码语言:javascript
复制
ascii_term_id.decode()

而不是

代码语言:javascript
复制
str(ascii_term_id)

代码

代码语言:javascript
复制
print( b'0500'.decode() )
print( str(b'0500') )

在Python 2上给出了

代码语言:javascript
复制
0500
0500

但是在Python 3上给出了

代码语言:javascript
复制
0500
b'0500'

编辑:

你只需要

代码语言:javascript
复制
print('ascii_term_id? "' + ascii_term_id.decode() + '"')

因为decode()bytes转换为string (Python3),而您不再需要str()

代码语言:javascript
复制
ascii_term_id = b'0500'

print( type( ascii_term_id ) )
print( type( ascii_term_id.decode() ) )

print('ascii_term_id? "' + ascii_term_id.decode() + '"')

Python 2:

代码语言:javascript
复制
<type 'str'>
<type 'unicode'>
ascii_term_id? "0500"

Python 3

代码语言:javascript
复制
<class 'bytes'>
<class 'str'>
ascii_term_id? "0500"
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68447316

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档