![](/img/trans.png)
[英]How can I get a string(Mix of digit and char) up to last digit using regex in python?
[英]How can I get the string of 5 digit hexadecimal in Python?
我有一個 integer 轉換為十六進制,如下所示:
int_N = 193402
hex_value = hex(int_N)
它給了我以下十六進制: 0x2f37a 。
我想將十六進制轉換為字符串。
我試過這個:
bytes.fromhex(hex_value[2:]).decode('ASCII')
# [2:] to get rid of the 0x
但是,它給了我這個錯誤:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf6 in position 1: ordinal not in range(128)
然后我嘗試使用decode('utf-8') 而不是 ASCII ,但它給了我這個錯誤:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 1: invalid start byte
有什么建議可以解決這個問題嗎? 為什么它沒有將十六進制 '0x2f37a' 轉換為字符串?
在閱讀了一些文檔之后,我認為十六進制可能應該包含偶數個數字才能轉換為字符串,但由於我使用的是 hex() 並且它給了我這個值,所以我無法這樣做或做到這一點。
感謝並非常感謝任何幫助!
我假設(可能是錯誤的)您的 int_N 是 unicode 代碼點。
>>> int_N = 193402
>>> chr(int_N)
'\U0002f37a'
您應該查看 struct 和 binascii 模塊。
import struct
import binascii
int_N = 193402
s = struct.Struct(">l")
val = s.pack(int_N)
output = binascii.hexlify(val)
print(output) #0002f37a
在 PMOTW3了解更多關於 c_type 打包的信息。
如果您只是想將其轉換為字符串,沒有其他要求,那么這是可行的(我將在此處將其填充為 8 個字符):
int_N = 193402
s = hex(int_N)[2:].rjust(8, '0') # get rid of '0x' and pad to 8 characters
print(s, type(s))
Output:
0002f37a <class 'str'>
...證明它是一個字符串類型。 如果您對獲取單個字節感興趣,那么這樣的事情將證明:
for b in bytes.fromhex(s):
print(b, type(b))
Output:
0 <class 'int'>
2 <class 'int'>
243 <class 'int'>
122 <class 'int'>
...顯示所有四個字節(來自八個十六進制數字)並證明它們是整數。 這里的關鍵是偶數個字符,我選擇了 8) 以便fromhex()
可以對其進行解碼。 奇數字節將給出ValueError
。
現在您可以隨意使用字符串或字節。
使用 f 字符串(格式字符串)以您喜歡的方式格式化數字。 以下是十六進制和二進制的各種 forms 的示例:
>>> n=193402
>>> f'{n:x} {n:08x} {n:#x} {n:020b}'
'2f37a 0002f37a 0x2f37a 00101111001101111010'
請參閱格式規范迷你語言。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.