共計 498 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,可以使用 hex()
函數將整數轉換為十六進制字符串。
以下是使用 hex()
函數輸出十六進制的示例:
num = 255
hex_value = hex(num)
print(hex_value) # 輸出:0xff
請注意,hex()
函數返回的是一個字符串,表示整數的十六進制表示形式。如果需要去掉前綴 0x
,可以使用字符串切片操作或使用format()
函數:
num = 255
hex_value = hex(num)[2:] # 切片操作去掉前綴 0x
print(hex_value) # 輸出:ff
hex_value = format(num, 'x') # 使用 format()函數
print(hex_value) # 輸出:ff
如果希望將一個字符串轉換為相應的十六進制表示形式,可以使用 str.encode()
方法:
text = "hello"
hex_value = text.encode().hex()
print(hex_value) # 輸出:68656c6c6f
在這個例子中,str.encode()
方法將字符串轉換為字節序列,而 .hex()
方法將字節序列轉換為十六進制字符串。
丸趣 TV 網 – 提供最優質的資源集合!
正文完