Chris Nguyen
Chris Nguyen

Reputation: 160

Python chr() explain

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!

Upvotes: 4

Views: 3648

Answers (2)

o11c
o11c

Reputation: 16136

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.

Upvotes: 0

John Hua
John Hua

Reputation: 1456

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

Upvotes: 1

Related Questions