我正在尝试将十六进制数据转换为ASCII,然后使用列表名称后跟ASCII数据显示ASCII数据。
如果response = ''
显示no data
和response = 'Hex data'
,请将其转换为ASCII数据。我已编写代码,但无法获得预期的输出。
我的代码如下:
data = [{ "Name":"Activate1 Configuration No.:\t", "response":''},
{ "Name":"Activate2 Configuration No.:\t","response":'62 F1 8C 30 30 30 30 30 30 30 30 31 31 35 36 38 36 38 31'},
{ "Name":"Activate3 Configuration No.:\t","response":''}]
def function(ASCII):
if(ASCII == 1):
BResponse = response.replace(' ','')
BResponse = BResponse.decode('hex')
BResponse = BResponse[3:]
print('response' + response)
print ('ASCII' + BResponse)
else:
print('response' + response)
for readdta in data:
temp_text = '{0}'.format(readdta['Name'])
response = '{0}'.format(readdta['response'])
if(function(1)):
if(response == ''):
print 'No data'
else:
print 'temp_text '+ BResponse
我期待输出如下:
Activate1 Configuration No.: No data
Activate2 Configuration No.: 0000000011568681 (ASCII Data)
Activate3 Configuration No.: No data
答案 0 :(得分:1)
function
没有返回任何内容,因此if function(1)
总是会失败,因此您永远不会获得任何预期的输出(尽管您会得到一堆明显意外的输出)。< / p>
答案 1 :(得分:1)
您可以直接操作数据,无需使用函数,如下所示:
data = [{ "Name":"Activate1 Configuration No.:\t", "response":''},
{ "Name":"Activate2 Configuration No.:\t","response":'62 F1 8C 30 30 30 30 30 30 30 30 31 31 35 36 38 36 38 31'},
{ "Name":"Activate3 Configuration No.:\t","response":''}]
for readdta in data: #for loop all the data
temp_text = '{0}'.format(readdta['Name']) #get the value of Name
response = '{0}'.format(readdta['response']).replace(' ','') #get the value of response
if response == "":
response = 'No data'
else:
response = response.decode('hex')[3:] #decode the response
print temp_text + response #print them out
输出:
Activate1 Configuration No.: No data
Activate2 Configuration No.: 0000000011568681
Activate3 Configuration No.: No data