May-01-2017, 02:25 AM
what function can convert a string containing unprintable binary characters to source code compatible escape sequences that can restore that binary character when that escape sequence gets parsed as part of a source code string literal?
i thought it to be repr() but it isn't since it does not convert some character values to the escape sequence.
i thought it to be repr() but it isn't since it does not convert some character values to the escape sequence.
Output:Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> ord('\377')
255
>>> chr(255)
'\xff'
>>> repr(chr(255))
"'\xff'"
>>> print(repr(chr(255)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character '\xff' in position 1: ordinal not in range(128)
>>> a=repr(chr(255))
>>> a
"'\xff'"
>>> a[0]
"'"
>>> a[1]
'\xff'
>>> a[2]
"'"
>>> repr(chr(255))[1]
'\xff'
>>>
in the above, it can be seen that the character with the binary value of 255 gets "converted" to a single character with the value of 255. it is the python interactive tool showing us the \xff to represent that value. i want a function that converts that character (value 255) to \xff which works in source code:Output:Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> len('\xff')
1
>>> ord('\xff')
255
>>>
this shows how a script can code eiither \xff or \377 to get a single character with the value 255. a function that can convert to either hexadecimal form or octal form is suitable.Output:lt1/forums /home/forums 13> cat ff.py
c = '\xff'
print(len(c))
print(ord(c))
c = '\377'
print(len(c))
print(ord(c))
lt1/forums /home/forums 14> py3 ff.py
1
255
1
255
lt1/forums /home/forums 15>
then there is reprlib.repr(). but it has exactly the same issues. before i go code up my own version of repr() can someone point me to the correct function somewhere within python?