I found the Python 3 documentation on chr
and ord
to be a little unclear as to how they relate to the two main textual data types: str
and bytes
. Or maybe I'm overthinking it.
Here is what I think probably happens, but can you let me know if I'm right?
ord()
takes as input a single-character str
and returns an int
. The input is a str
just like any other str
in Python 3. In particular, it is not bytes
encoded in some specific Unicode format like UTF-8, rather it represents Unicode Code Points in Python's internal str
format.chr()
takes as input an int
, and returns a single character str
. The returned str
is just like any other str
in Python, and similarly is not a specific encoding using bytes
.ord()
or chr()
deal with bytes
, nor do they deal with specific Unicode formats like UTF-8, they are only dealing with Python's internal str
representation which deals more abstractly with Unicode Code Points.The Python ord() function converts a character into an integer that represents the Unicode code of the character. Similarly, the chr() function converts a Unicode code character into the corresponding string.
Python chr() and ord() Python's built-in function chr() is used for converting an Integer to a Character, while the function ord() is used to do the reverse, i.e, convert a Character to an Integer. Let's take a quick look at both these functions and understand how they can be used.
The chr() function returns the character that represents the specified unicode.
For example, ord('a') returns the integer 97, ord('€') (Euro sign) returns 8364. This is the inverse of chr() for 8-bit strings and of unichr() for Unicode objects. If a Unicode argument is given and Python is built with UCS2 Unicode, then the character's code point must be in the range [0..
You are right.
ord()
and chr()
deal only with single-character strings.
Their documentation is quite clear about that:
>>> help(ord)
ord(c, /)
Return the Unicode code point for a one-character string.
>>> help(chr)
chr(i, /)
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
Use str.encode
/ bytes.decode
for conversion to/from bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With