Search code examples
pythonescapingord

How to pass escape sequences to python's ord() function?


I am using Python 3. I am also using the ord() function in my script. If I type ord('\xff') in the console it returns 255

Is there a way to insert \xff (which is stored in a variable) into the ord() function without getting

error:
TypeError: ord() expected a character, but string of length 4 found

How does ord('\xff') work? ord() doesn't read strings? Whats it reading then?


Solution

  • Are you receiving this data from some user input? In this case, what you meant to read as a single character was read literally as a string of size 4.

    In [1320]: v = input()
    \xff
    
    In [1321]: v
    Out[1321]: '\\xff'
    

    One workaround is to use ast.literal_eval:

    In [1326]: import ast
    
    In [1327]: v = ast.literal_eval('"{}"'.format(v))
    
    In [1329]: ord(v)
    Out[1329]: 255