Python:Ascii character<->decimal representation conversion

本小妞迷上赌 提交于 2020-01-01 02:10:37

问题


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

How can I do that?


回答1:


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.




回答2:


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




回答3:


ord




回答4:


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


来源:https://stackoverflow.com/questions/4387138/pythonascii-character-decimal-representation-conversion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!