4

So I am pretty sure this is a dumb question, but I am trying to get a deeper understanding of the python chr() function. Also, I am wondering if it is possible to always have the integer argument three digits long, or just a fixed length for all ascii values?

chr(20) ## '\x14'
chr(020) ## '\x10'

Why is it giving me different answers? Does it think '020' is hex or something? Also, I am running Python 2.7 on Windows! -Thanks!

4

2 回答 2

1

There is nothing to do with char. It is all about Numeric literals. And it is cross-language. 0 indicates oct and 0x indicates hex.

print 010 # 8
print 0x10 # 16
于 2015-01-28T04:07:17.690 回答
0

It makes sense to explain chr and ord together.

You are obviously using Python2 (because of the octal problem, Python3 requires 0o as the prefix), but I'll explain both.

In Python2, chr is a function that takes any integer up to 256 returns a string containing just that extended-ascii character. unichr is the same but returns a unicode character up to 0x10FFFF. ord is the inverse function, which takes a single-character string (of either type) and returns an integer.

In Python3, chr returns a single-character unicode string. The equivalent for byte strings is bytes([v]). ord still does both.

于 2015-07-03T02:37:07.480 回答