函数 ord() 的功能

functionality of function ord()

谁能解释一下函数 ord 在这段代码中的作用? 该代码旨在将以字符串形式编写的数字相乘(不使用 int())。

def multiply(num1, num2):
    """
    :type num1: str
    :type num2: str
    :rtype: str
    """

    res1, res2 = 0, 0 
    for d in num1:
        print(d)
        print(ord(d))
        print(ord('0'))
        res1 = res1 * 10 + (ord(d) - ord('0'))
    for d in num2:
        res2 = res2 * 10 + (ord(d) - ord('0'))
    return str(res1 * res2)

ord(d) - ord('0') 如何最终 return 得到正确的结果。我不明白 ord 到底是做什么的。

ord('0') 总是 48(这是我打印时得到的结果)吗?

returns 表示字符 Unicode 代码 点的整数

ord 是一个函数,它接受一个字符和 returns unicode 与该字符相关联的数字。 unicode 构造数字 0-9 ord("9")-ord("0") 的方式将导致 9ord of 0 是 48,数字从那里开始计数:“1”是 49,“2”是 50 等。该代码删除了 unicode 中数字的偏移量,以便您得到数字是的数字为了。所以 ord("2") - ord("0") 的计算结果为 50 - 482.

ord 的逆运算是 chr,它将 return 字符赋予一个数字。 chr(48)"0" 您可以尝试使用这些函数,也可以查看 Ascii Table(包含在 unicode 中)以了解有关字符在计算机中的表示方式的更多信息。