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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。