在 Python 中获取字符的 ASCII 值
    
    
            Muhammad Waiz Khan
    2021年2月28日
    
    Python
    Python ASCII
    
本教程将解释在 Python 中获取一个字符的 ASCII 值的各种方法。ASCII 字符编码是电子通信的标准字符编码。所有的常规字符都有一些 ASCII 值,用于表示计算机和其他电子设备中的文本。例如,a 的 ASCII 值是 97,A 的 ASCII 值是 65。
在 Python 中使用 ord() 函数获取字符的 ASCII 值
    
ord() 函数将一个字符作为输入,并以整数返回该字符的十进制等效 Unicode 值。我们将字符传给 ord() 函数,得到 ASCII 字符的 ASCII 值。如果我们将一些非 ASCII 字符,如ß传递给 ord() 函数,它将返回 Unicode 值,因为ß不是一个 ASCII 字符。
下面的示例代码演示了如何使用 ord() 函数来获取字符的 ASCII 值。
print(ord("a"))
print(ord("A"))
print(ord(","))
输出:
97
65
44
我们也可以使用 for 循环获取字符串中每个字符的 ASCII 值,如下例代码所示。
string = "Hello!"
for ch in string:
    print(ch + " = " + str(ord(ch)))
输出:
H = 72
e = 101
l = 108
l = 108
o = 111
! = 33
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe