简体   繁体   English

将Python字符串转换为其ASCII表示形式

[英]Convert Python string to its ASCII representants

How do I convert a string in Python to its ASCII hex representants? 如何将Python中的字符串转换为ASCII十六进制表示符?

Example: I want to result '\\x00\\x1b\\xd4}\\xa4\\xf3\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' in 001bd47da4f3 . 例如:我想导致'\\x00\\x1b\\xd4}\\xa4\\xf3\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'001bd47da4f3

>>> text = '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'.rstrip('\0')
>>> print "".join("%02x" % ord(c) for c in text)
001bd47da4f3

As per martineau's comment, here is the Python 3 way: 根据martineau的评论,这是Python 3的方式:

>>> "".join(format(ord(c),"02x") for c in text)

With python 2.x you can encode a string to it's hex representation. 使用python 2.x,您可以将字符串编码为十六进制表示。 It will not work with python3.x 它不适用于python3.x

>>> print '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'.encode("hex")
'001bd47da4f300000000000000000000'

It's not entirely clear if you have a literal string containing the escapes (so basically r'\\x00\\x1b' and so on) or not. 如果你有一个包含转义的文字字符串(所以基本上是r'\\ x00 \\ x1b'等等)或者没有完全清楚。 Also, it's unclear why you don't expect the trailing zeroes, but you can remove those before the encode using .rstrip("\\x00") 此外,还不清楚为什么你不期望尾随零,但你可以使用.rstrip(“\\ x00”)删除编码之前的零

Alternative: 替代方案:

[Python 2.7]
>>> data = '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> import binascii
>>> binascii.b2a_hex(data.rstrip('\x00'))
'001bd47da4f3'
>>>

[Python 3.1.2]
>>> data = b'\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> import binascii
>>> binascii.b2a_hex(data.rstrip(b'\x00'))
b'001bd47da4f3'
>>>

Here's another answer that ought to work with all Python versions from 3.x all the way back to 2.0 (min version according to pyqver ). 这是另一个答案应该适用于从3.x到2.0的所有Python版本(根据pyqver的最小版本)。 Despite that, because it's based on a simple table (not dict) lookup, it should also be relatively quick. 尽管如此,因为它基于一个简单的表(不是字典)查找,它也应该相对较快。

A little one-time set-up is required, but is very simple and avoids using the any of the many enhancements that have were added (or removed) along the way in a quest for version independence. 需要一点一次的设置,但是非常简单,并且避免使用在寻求版本独立性的过程中添加(或删除)的任何增强功能。

numerals = "0123456789abcdef"
hexadecimal = [i+j for i in numerals for j in numerals]

text = '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'    
print ''.join([hexadecimal[ord(c)] for c in text.rstrip('\0')])
# 001bd47da4f3

binascii.hexlify() : binascii.hexlify()

import binascii

byte_string = '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 
print binascii.hexlify(byte_string.rstrip('\x00'))

# -> 001bd47da4f3

See @John Machin's answer . @John Machin的回答

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM