Python:Ascii 字符<->十进制表示转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4387138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python:Ascii character<->decimal representation conversion
提问by Alpagut
Hi I need to be able to convert a ascii character into its decimal equivalent and vice-versa.
嗨,我需要能够将 ascii 字符转换为其十进制等价物,反之亦然。
How can I do that?
我怎样才能做到这一点?
采纳答案by Adam Matan
回答by Karl Knechtel
Use ordto convert a character into an integer, and chrfor vice-versa.
使用ord一个字符转换为整数,并chr为反之亦然。
回答by Kushan Gunasekera
You have to use ord()and chr()Built-in Functionsof Python. Check the below explanations of those functions from Python Documentation.
你必须使用ord()和内置功能的Python。查看Python 文档中对这些函数的以下说明。chr()
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().
给定一个表示一个 Unicode 字符的字符串,返回一个表示该字符的 Unicode 代码点的整数。例如,ord('a') 返回整数 97,而 ord('')(欧元符号)返回 8364。这是 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().
返回表示其 Unicode 代码点为整数 i 的字符的字符串。例如,chr(97) 返回字符串 'a',而 chr(8364) 返回字符串 ''。这是 ord() 的倒数。
So this is the summary from above explanations,
所以这是以上解释的总结,
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

