簡體   English   中英

在python中將字符串分配給變量

[英]Assigning strings to a variable in python

考慮下面的字符串,該字符串將作為函數的輸入給出。

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")

能做到嗎?

我想在這里做到這一點,讓我知道是否需要更改:

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']

這是一些代碼,希望對您有所幫助。 我試圖添加許多評論以解釋發生了什么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM