在python中为字符串赋值

时间:2016-08-24 08:11:04

标签: python python-2.7

考虑下面的字符串,它将作为函数的输入。

  

01 02 01 0D A1 D6 72 02 00 01 00 00 00 00 53 73 F2

突出显示的部分是我需要的地址。

如果前面的字节是1,那么我只需要6个八位字节并将其分配给变量。

如果它大于1,我应该读取6 * Num(前一个值)并为每个变量分配6个八位字节。

目前我正在静态分配。

def main(line_input):
    Device = ' '.join(line_input[9:3:-1])
    Length = line_input[2]
    var1 = line_input[3]
main("01 02 02 0D A1 D6 72 02 00 01 00 00 00 00 53 73 F2")

可以这样做吗?

2 个答案:

答案 0 :(得分:0)

在这里我认为这样做,让我知道是否有任何需要改变的事情:

import string 

def address_extract(line_input):
    line_input = string.split(line_input, ' ')
    length = 6 * int(line_input[2]) 
    device_list = []
    for x in range(3, 3+length, 6):
        if x+6 > len(line_input):
            print "Length multiplier too long for input string"
        else:
            device_list.append(' '.join(line_input[x:x+6]))

    return device_list

print address_extract("01 02 02 0D A1 D6 72 02 00 01 00 00 00 00 53 73 F2")
#output = ['0D A1 D6 72 02 00', '01 00 00 00 00 53']

答案 1 :(得分:0)

以下是一些我希望能为您提供帮助的代码。我试图添加许多评论来解释正在发生的事情

import binascii
import struct

#note python 3 behaves differently and won't work with this code (personnaly I find it easyer for strings convertion to bytes)
def main(line_input):
    formated_line = line_input.split(" ") #I start by cutting the input on each space character
    print formated_line #the output is a list. Each element is composed of 2 chars
    formated_line = [binascii.unhexlify(xx) for xx in formated_line] #create a list composed of unhelified bytes of each elements of the original list
    print formated_line #the output is a list of bytes char
    #can be done in one step but I try to be clearer as you are nee to python (moereover this is easyer in python-3.x)
    formated_line = map(ord, formated_line) #convert to a list of int (this is not needed in python 3)
    print formated_line
    Length = formated_line[2] #this is an int
    unformated_var1 = formated_line[3:3+(6*length)] #keep only interesting data
    #now you can format your address

main("01 02 02 0D A1 D6 72 02 00 01 00 00 00 00 53 73 F2")
#if the input comes from a machine and not a human, they could exchange 17bytes instead of (17x3)characters
#main("\x01\x02\x02\x0D\xA1\xD6\x72\x02\x00\x01\x00\x00\x00\x00\x53\x73\xF2")
#then the parsing could be done with struct.unpack