簡體   English   中英

將Python字符串轉換為其ASCII表示形式

[英]Convert Python string to its ASCII representants

如何將Python中的字符串轉換為ASCII十六進制表示符?

例如:我想導致'\\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

根據martineau的評論,這是Python 3的方式:

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

使用python 2.x,您可以將字符串編碼為十六進制表示。 它不適用於python3.x

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

如果你有一個包含轉義的文字字符串(所以基本上是r'\\ x00 \\ x1b'等等)或者沒有完全清楚。 此外,還不清楚為什么你不期望尾隨零,但你可以使用.rstrip(“\\ x00”)刪除編碼之前的零

替代方案:

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

這是另一個答案應該適用於從3.x到2.0的所有Python版本(根據pyqver的最小版本)。 盡管如此,因為它基於一個簡單的表(不是字典)查找,它也應該相對較快。

需要一點一次的設置,但是非常簡單,並且避免使用在尋求版本獨立性的過程中添加(或刪除)的任何增強功能。

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

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

@John Machin的回答

暫無
暫無

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

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