Stephen
Stephen

Reputation: 8859

How do chr() and ord() relate to str and bytes?

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?

Upvotes: 7

Views: 7052

Answers (1)

fferri
fferri

Reputation: 18950

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.

Upvotes: 0

Related Questions