2011-10-23 3 views
2

PHP에서 unpack()에는 "입력 끝날 때까지이 형식 반복"을 의미하는 "*"플래그가 있습니다. 예를 들어, 97, 98, 99를 인쇄합니다.팩 형식 문자열의 자동 반복 플래그

$str = "abc"; 
$b = unpack("c*", $str); 
print_r($b); 

Python에는 다음과 같은 것이 있습니까? 물론 할 수 있습니다

str = "abc" 
print struct.unpack("b" * len(str), str) 

그러나 더 좋은 방법이 있는지 궁금합니다.

+0

'[문자열에 난에 대한 ORD (I)]' – JBernardo

+0

JBernardo, 당신은이를 이동하는 것을 고려한다 대답. – nagisa

답변

3

struct.unpack에 내장 된 이러한 기능은 없지만, 그런 기능을 정의 할 수 있습니다 :

import struct 

def unpack(fmt, astr): 
    """ 
    Return struct.unpack(fmt, astr) with the optional single * in fmt replaced with 
    the appropriate number, given the length of astr. 
    """ 
    # http://stackoverflow.com/a/7867892/190597 
    try: 
     return struct.unpack(fmt, astr) 
    except struct.error: 
     flen = struct.calcsize(fmt.replace('*', '')) 
     alen = len(astr) 
     idx = fmt.find('*') 
     before_char = fmt[idx-1] 
     n = (alen-flen)/struct.calcsize(before_char)+1 
     fmt = ''.join((fmt[:idx-1], str(n), before_char, fmt[idx+1:])) 
     return struct.unpack(fmt, astr) 

print(unpack('b*','abc')) 
# (97, 98, 99) 
+0

감사합니다. 도움이되었습니다. – georg