pythonstringord

functionality of function ord()


can anyone explain what the function ord does in this code? The code is meant to multiply the numbers written as strings (without using 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)

How can ord(d) - ord('0') finally return the correct result. I don't understand what exactly ord does.

Is ord('0') always 48 (which is what I get when I print)?


Solution

  • ord is a function that takes a character and returns the number that unicode associates that character with. The way unicode structures the digits 0-9 ord("9")-ord("0") will result in 9. ord of 0 is 48 and the digits count up from there: "1" is 49, "2" is 50 etc. That code removes the offset of the digits in unicode so that you get the number that the digit is in order. So ord("2") - ord("0") evaluates to 50 - 48 which is 2.

    The inverse of ord is chr which will return the character given a number. chr(48) is "0" You can play around with these functions as well as looking at an Ascii Table (which is contained in unicode) to learn more about how characters are represented in computers.