Python:Ascii character<->decimal representation conversion

后端 未结 4 512
情歌与酒
情歌与酒 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:47
    num=ord(char)
    char=chr(num)
    

    For example,

    >>> ord('a')
    97
    >>> chr(98)
    'b'
    

    You can read more about the built-in functions in Python here.

    0 讨论(0)
  • 2021-02-04 04:48

    Use ord to convert a character into an integer, and chr for vice-versa.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-04 05:05

    ord

    0 讨论(0)
提交回复
热议问题