Python:Ascii character<->decimal representation conversion

后端 未结 4 516
情歌与酒
情歌与酒 2021-02-04 04:13

Hi I need to be able to convert a ascii character into its decimal equivalent and vice-versa.

How can I do that?

4条回答
  •  粉色の甜心
    2021-02-04 04:53

    You have to use ord() and chr() Built-in Functions of Python. Check the below explanations of those functions from Python Documentation.

    ord()

    Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().

    chr()

    Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord().

    So this is the summary from above explanations,

    • ord() is the inverse of chr()
    • chr() is the inverse of ord()

    Check this quick example get an idea how this inverse work,

    >>> ord('H')
    72
    >>> chr(72)
    'H'
    >>> chr(72) == chr(ord('H'))
    True
    >>> ord('H') == ord(chr(72))
    True
    

提交回复
热议问题