Search code examples
pythonstringbytepycrypto

How can I construct a Python string that is 16 bytes long?


When I make a Python string of one character, i.e.

txt = "h"

and I check its size, I get

import sys
sys.getsizeof(txt)
34

If one character is 34 bytes, how do I make a String of 16 byes?

P.S. I'm playing around with PyCrypto AES, in OFB Mode, which required input of 16 bytes


Solution

  • getsizeof does not return the actual size of the string but it accounts for additional garbage collector overhead. As shown bellow test starts as an empty string but memory allocated for it is not zero due to reasons listed above.

    >>> test = ""
    >>> sys.getsizeof(test)
    37
    >>> test = "" + "h"
    >>> sys.getsizeof(test)
    38
    >>> test = "" + "h" + "h"
    >>> sys.getsizeof(test)
    39
    >>>
    

    To create a 16 bytes string, one way would be:

    >>> test = " " * 16
    >>> sys.getsizeof(test)
    53
    

    53 - 37 = 16 bytes