Python 的 hex(~) 方法將整數轉換為前綴為 "0x" 的小寫十六進製字符串。如果提供的輸入不是整數,則必須實現 __index__() 方法來返回整數。
參數
1. x | integer
要轉換為小寫十六進製字符串的整數。
返回值
以 "0x" 為前綴的整數的轉換後的十六進製字符串。
例子
基本用法
要返回 87 的小寫十六進製字符串:
hex(87)
'0x57'
請注意,"0x" 僅表示它是一個十六進製字符串。
__index__()方法
要將 hex(~) 方法與實現 __index__() 方法的輸入結合使用:
class score:
james = 20
sally = 40
tom = 30
def __index__(self):
return self.james + self.sally + self.tom
hex(score())
'0x5a'
我們提供 score 類的實例作為 hex(~) 方法的輸入。盡管實例本身不是整數,但由於它返回一個整數(james + sally + tom 的總和),在本例中為 90 ,因此 hex(~) 返回 90 的十六進製字符串。
TypeError
如果我們提供整數以外的輸入:
hex('Hi')
TypeError: 'str' object cannot be interpreted as an integer
相關用法
- Python hex()用法及代碼示例
- Python hex用法及代碼示例
- Python help()用法及代碼示例
- Python help方法用法及代碼示例
- Python hashlib.sha3_256()用法及代碼示例
- Python NumPy hstack方法用法及代碼示例
- Python BeautifulSoup has_attr方法用法及代碼示例
- Python hasattr方法用法及代碼示例
- Python http.HTTPStatus用法及代碼示例
- Python hashlib.sha3_512()用法及代碼示例
- Python hashlib.shake_256()用法及代碼示例
- Python hashlib.shake_128()用法及代碼示例
- Python NumPy hypot方法用法及代碼示例
- Python hashlib.blake2s()用法及代碼示例
- Python hashlib.blake2b()用法及代碼示例
- Python hasattr()用法及代碼示例
- Python html.escape()用法及代碼示例
- Python statistics harmonic_mean()用法及代碼示例
- Python html.unescape()用法及代碼示例
- Python math hypot()用法及代碼示例
- Python hash()用法及代碼示例
- Python hashlib.sha3_224()用法及代碼示例
- Python OpenCV haveImageReader()用法及代碼示例
- Python NumPy hsplit方法用法及代碼示例
- Python http.client.HTTPConnection.set_tunnel用法及代碼示例
注:本文由純淨天空篩選整理自Arthur Yanagisawa大神的英文原創作品 Python | hex method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
