cjwert
cjwert

Reputation: 89

TypeError: 'int' object is not subscriptable

Why does this code snippet result in: TypeError 'int' object is not subscriptable?

return (bin(int(hexdata)[2:].zfill(16)))

hexdata is a hexadecimal string. For example, it may be 0x0101.

Upvotes: 0

Views: 4712

Answers (2)

falsetru
falsetru

Reputation: 369064

You're doing this:

>>> int('1234')[2:]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'

>>> 1234[2:]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'

If you intended to remove the first two character, use following:

>>> int('1234'[2:])
34

If the orignal string is hexadecimal representation, you should pass optional base argument 16

>>> int('1234'[2:], 16)
52

If [2:] is used to remove 0b generated by bin (not to remove leading characters from the original string), then following is what you want.

>>> int('0x1234', 16) # No need to remove leading `0x`
4660
>>> int('0x1234', 0)  # automatically recognize the number's base using the prefix
4660
>>> int('1234', 16)
4660
>>> bin(int('1234', 16))
'0b1001000110100'
>>> bin(int('1234', 16))[2:]
'1001000110100'
>>> bin(int('1234', 16))[2:].zfill(16)
'0001001000110100'

BTW, you can use str.format or format instead of bin + str.zfill:

>>> '{:016b}'.format(int('1234', 16))
'0001001000110100'
>>> format(int('1234', 16), '016b')
'0001001000110100'

UPDATE

If you specify 0 as a base, int will automatically recognize the number's base using the prefix.

>>> int('0x10', 0)
16
>>> int('10', 0)
10
>>> int('010', 0)
8
>>> int('0b10', 0)
2

Upvotes: 4

paxdiablo
paxdiablo

Reputation: 881393

Parentheses in the wrong place. Assuming you have a string like "0x0101" where you want to end up with a 16-digit binary string:

bin(int(hexdata,16))[2:].zfill(16)

The int(X,16) call interprets that as a hex number (and can accept a number of the form 0xSomething). Then bin(X) turns that into a string of the form 0b01010101.

The [2:] then gets rid of the 0b at the front and zfill(16) fills that out to 16 "bits".

>>> bin(int("0x0102",16))[2:].zfill(16)
'0000000100000010'

Upvotes: 1

Related Questions