Search code examples
pythonpython-3.xord

TypeError: ord() expected string of length 1, but int found


I try to implement a AES algorithm in python 3.While implementing this I found an error in ord() function.I just try to convert the code from python 2.3 to python 3.How can I fix the error? My code line is :

key = map(ord, key)

Thanks in advance


Solution

  • Your key variable is already a bytes object (str in Py2). In Py2, str is a sequence of length 1 str, so you need ord to convert to a sequence of int.

    In Py3, bytes objects are sequences of ints from 0 to 255 inclusive. Basically, in Python 2, you needed map(ord, key) to convert from str to sequence (list) of int, in Python 3, you don't need to perform the conversion at all unless you need to mutate the sequence, and even then, you can simply do bytearray(key) to make a mutable copy of the original bytes.

    Note that Py2.6+ has the bytearray type and it behaves the same as it does in Py3 (a mutable sequence of ints), so you could likely write 2/3 portable code by just using bytearray(key) everywhere (and it will be faster than map(ord, key) to boot).