programing tip

Python 3.1.1 문자열을 16 진수로

itbloger 2020. 11. 23. 07:53
반응형

Python 3.1.1 문자열을 16 진수로


내가 사용하려고 str.encode()하지만 난 얻을

>>> "hello".encode(hex)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be string, not builtin_function_or_method

여러 변형을 시도해 보았는데 모두 Python 2.5.2에서 작동하는 것 같습니다. 그렇다면 Python 3.1에서 작동하도록하려면 어떻게해야합니까?


hex코덱 3.x로에 흡착 한 사용 binascii하는 대신 :

>>> binascii.hexlify(b'hello')
b'68656c6c6f'

당신은 이미 좋은 대답을 얻었지만, 당신도 약간의 배경에 관심이있을 것이라고 생각했습니다.

먼저 따옴표가 누락되었습니다. 그것은해야한다:

"hello".encode("hex")

둘째,이 코덱은 Python 3.1로 이식되지 않았습니다. 를 참조하십시오 여기 . 이러한 코덱이 Python 3에 포함되어야하는지 아니면 다른 방식으로 구현되어야하는지 여부는 아직 결정되지 않은 것 같습니다.

해당 버그에 첨부 된 diff 파일 을 보면 제안 된 구현 방법을 볼 수 있습니다.

import binascii
output = binascii.b2a_hex(input)

그런데 binascii 방법은 더 쉽습니다

>>> import binascii
>>> x=b'test'
>>> x=binascii.hexlify(x)
>>> x
b'74657374'
>>> y=str(x,'ascii')
>>> y
'74657374'
>>> x=binascii.unhexlify(x)
>>> x
b'test'
>>> y=str(x,'ascii')
>>> y
'test'

도움이 되었기를 바랍니다. :)


Python 3에서는 문자열을 바이트로 인코딩하고 hex()메서드를 사용하여 문자열을 반환합니다.

s = "hello".encode("utf-8").hex()
s
# '68656c6c6f'

선택적으로 문자열을 다시 바이트로 변환합니다.

b = bytes(s, "utf-8")
b
# b'68656c6c6f'

Python 3에서 모든 문자열은 유니 코드입니다. 당신이 문자열로 유니 코드 객체를 인코딩하는 경우 일반적으로, 당신은 사용 .encode('TEXT_ENCODING')하기 때문에, hex텍스트 인코딩하지, 당신은 사용해야 codecs.encode()임의의 코덱을 처리 할 수 있습니다. 예를 들면 :

>>>> "hello".encode('hex')
LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
>>>> import codecs
>>>> codecs.encode(b"hello", 'hex')
b'68656c6c6f'

다시 말하지만, "hello"는 유니 코드이므로 16 진수로 인코딩하기 전에 바이트 문자열로 표시해야합니다. 이것은 방법을 사용하는 원래 접근 방식과 더 비슷할 수 있습니다 encode.

의 차이 binascii.hexlify와는 codecs.encode다음과 같습니다 :

  • binascii.hexlify

    이진 데이터의 16 진수 표현.

    반환 값은 bytes 객체입니다.

    유형 : builtin_function_or_method

  • codecs.encode

    encode(obj, [encoding[,errors]]) -> object

    Encodes obj using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a ValueError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle ValueErrors.

    Type: builtin_function_or_method


base64.b16encode and base64.b16decode convert bytes to and from hex and work across all Python versions. The codecs approach also works, but is less straightforward in Python 3.


The easiest way to do it in Python 3.x is:

>>> 'halo'.encode().hex()
'68616c6f'

If you manually enter a string into a Python Interpreter using the utf-8 characters, you can do it even faster by typing b before the string:

>>> b'halo'.hex()
'68616c6f'

Equivalent in Python 2.x:

>>> 'halo'.encode('hex')
'68616c6f'

Use hexlify - http://epydoc.sourceforge.net/stdlib/binascii-module.html


Yet another method:

s = 'hello'

h = ''.join([hex(ord(i)) for i in s]);

# outputs: '0x680x650x6c0x6c0x6f'

This basically splits the string into chars, does the conversion through hex(ord(char)), and joins the chars back together. In case you want the result without the prefix 0x then do:

h = ''.join([str(hex(ord(i)))[2:4] for i in s]);

# outputs: '68656c6c6f'

Tested with Python 3.5.3.

참고URL : https://stackoverflow.com/questions/2340319/python-3-1-1-string-to-hex

반응형