Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is chr(ord(c)) not equal to c in Python?

Tags:

python

I am reading the source code of testinfra in the Ansible module. I found the following lines of code:

    # Ansible return an unicode object but this is bytes ...
    # A simple test case is:
    # >>> assert File("/bin/true").content == open("/bin/true").read()
    stdout_bytes = b"".join((chr(ord(c)) for c in out['stdout']))
    stderr_bytes = b"".join((chr(ord(c)) for c in out['stderr']))

It iterates over stdout, gets the integer ordinal of each character and converts it back to a one-character string. But what's the point?

like image 233
satoru Avatar asked May 04 '16 00:05

satoru


People also ask

What is CHR () and Ord () in Python?

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.

What is difference between Ord () and CHR () functions?

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.

What are the use of Ord () and CHR () function in Python explain with example?

Python ord() and chr() are built-in functions. They are used to convert a character to an int and vice versa. Python ord() and chr() functions are exactly opposite of each other.

What does the CHR () function do in Python?

The chr() function returns the character that represents the specified unicode.


1 Answers

When c is unicode-specific character (cannot be encoded in ASCII):

>>> ord(u'\u2020')
8224
>>> chr(ord(u'\u2020'))
ValueError: chr() arg not in range(256)

This is only true in Python2, as in Python3, unichr is removed and chr acts as unichr. This seems to be unusual behavior for such a library, since it would routinely throw an unexpected error that's executable-specific for any non-English locale.

like image 173
Alexander Huszagh Avatar answered Oct 05 '22 21:10

Alexander Huszagh