📜  获取字符python的十六进制代码(1)

📅  最后修改于: 2023-12-03 15:11:51.514000             🧑  作者: Mango

获取字符 Python 的十六进制代码

Python 可以通过内置函数 ord() 获取单个字符的 ASCII 码,进而将其转换为十六进制代码。

下面是一个示例代码:

char = 'Python'
for c in char:
    hex_code = hex(ord(c))
    print(f"The hex code of {c} is {hex_code}")

输出结果为:

The hex code of P is 0x50
The hex code of y is 0x79
The hex code of t is 0x74
The hex code of h is 0x68
The hex code of o is 0x6f
The hex code of n is 0x6e

解释:

首先定义了一个被获取的字符 char,在 for 循环中遍历这个字符串,使用 ord() 获取每个字符的 ASCII 码值,再使用内置函数 hex() 将 ASCII 码值转换为十六进制代码。最后输出结果,使用 f-string 格式化字符串。

这段代码中用到了许多 Python 的基本知识和语句,比如字符串和循环,内置函数和格式化输出等。对于初学者来说,这是一段相对简单易懂的代码。