我正在使用 Python 3。我还在脚本中使用了 ord() 函数。如果我ord('\xff')
在控制台中输入它会返回255
有没有办法在不获取的情况下将\xff
(存储在变量中)插入到ord()
函数中
error:
TypeError: ord() expected a character, but string of length 4 found
如何ord('\xff')
工作?ord() 不读取字符串?那它在读什么?
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