Python将字符串解压缩到数组中

时间:2012-06-18 23:21:39

标签: python arrays string

我每天都在使用Ruby,但我在Python中遇到了问题。我发现这些语言非常相似...但我从Ruby迁移有一些问题:)

请帮我在python中转换这个动作:

   string = "qwerty2012"
   (var, some_var, another_var)  = string.unpack("a1a4a*")

这应该返回三个带有解压缩值的变量:

   var         = "q"      # a1
   some_var    = "wert"   # a4
   another_var = "y2012"  # a*

帮我用Python代表它 谢谢!

5 个答案:

答案 0 :(得分:9)

s = "qwerty2012"
(a, b, c) = s[:1], s[1:5], s[5:]

答案 1 :(得分:5)

Python确实有一个名为struct的类似模块。它缺乏抓取其余字符串的能力,与Ruby and PHP lifted from Perl相同。你几乎可以到达那里:

>>> import struct
>>> s = 'qwerty2012'
>>> struct.unpack_from('1s4s', s)
('q', 'wert')
>>> def my_unpack(format, packed_string):
...    result = []
...    result.extend(struct.unpack_from(format, packed_string))
...    chars_gobbled = struct.calcsize(format)
...    rest = packed_string[chars_gobbled:]
...    if rest:
...        result.append(rest)
...    return result
...
>>> my_unpack('1s4s', 'qwerty2012')
['q', 'wert', 'y2012']
>>> my_unpack('1s4s', 'qwert')
['q', 'wert']
>>> [hex(x) for x in my_unpack('<I', '\xDE\xAD\xBE\xEF')]
['0xefbeadde']

我希望struct模块实现Perl的unpackpack的其余部分,因为它们是用于翻录二进制数据包的非常有用的功能,但是唉。

答案 2 :(得分:4)

s = "qwerty2012"
var, some_var, another_var = s[:1], s[1:5], s[5:]

将分别进行分配和收益:

q
wert
y2012

上述分配使用了Python Docs所描述的切片符号。这篇SO Good Primer for Python Slice Notation也给出了一个很好的解释。

答案 3 :(得分:2)

这是unpack的初步重新创建:

import re
import StringIO

def unpack(s, fmt):
    fs = StringIO.StringIO(s)
    res = []
    for do,num in unpack.pattern.findall(fmt):
        if num == '*':
            num = len(s)
        elif num == '':
            num = 1
        else:
            num = int(num)
        this = unpack.types[do](num, fs)
        if this is not None:
            res.append(this)
    return res

unpack.types = {
    '@': lambda n,s: s.seek(n),             # skip to offset
    'a': lambda n,s: s.read(n),             # string
    'A': lambda n,s: s.read(n).rstrip(),    # string, right-trimmed
    'b': lambda n,s: bin(reduce(lambda x,y:256*x+ord(y), s.read(n), 0))[2:].zfill(8*n)[::-1],   # binary, LSB first
    'B': lambda n,s: bin(reduce(lambda x,y:256*x+ord(y), s.read(n), 0))[2:].zfill(8*n)          # binary, MSB first
}
unpack.pattern = re.compile(r'([a-zA-Z@](?:_|!|<|>|!<|!>|0|))(\d+|\*|)')

适用于您的示例,

unpack("qwerty2012", "a1a4a*")  # -> ['q', 'wert', 'y2012']

但有一长串数据类型尚未实现(请参阅the documentation)。

答案 4 :(得分:1)

这可以简化您从Ruby的迁移:

import re
import struct

def unpack(format, a_string):
    pattern = r'''a(\*|\d+)\s*'''
    widths = [int(w) if w is not '*' else 0 for w in re.findall(pattern, format)]
    if not widths[-1]: widths[-1] = len(a_string) - sum(widths)
    fmt = ''.join('%ds' % f for f in widths)
    return struct.unpack_from(fmt, a_string)

(var, some_var, another_var) = unpack('a1a4a*', 'qwerty2012')  # also 'a1 a4 a*' OK
print (var, some_var, another_var)

输出:

('q', 'wert', 'y2012')