简体   繁体   English

TypeError:“ int”对象不可下标

[英]TypeError: 'int' object is not subscriptable

Why does this code snippet result in: TypeError 'int' object is not subscriptable ? 为什么此代码段会导致: TypeError 'int' object is not subscriptable

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

hexdata is a hexadecimal string. hexdata是十六进制字符串。 For example, it may be 0x0101 . 例如,它可以是0x0101

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 如果原始字符串是十六进制表示形式,则应传递可选的base参数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. 如果使用[2:]删除bin生成的0b (而不是删除原始字符串中的前导字符),则需要执行以下操作。

>>> 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 : 顺便说一句,您可以使用str.formatformat代替bin + str.zfill

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

UPDATE UPDATE

If you specify 0 as a base, int will automatically recognize the number's base using the prefix. 如果您将0指定为基数,则int将使用前缀自动识别数字的基数。

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

Parentheses in the wrong place. 括号放在错误的位置。 Assuming you have a string like "0x0101" where you want to end up with a 16-digit binary string: 假设您有一个像“ 0x0101”这样的字符串,您想以一个16位二进制字符串结尾:

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 ). int(X,16)调用将其解释为十六进制数字(并且可以接受格式为0xSomething )。 Then bin(X) turns that into a string of the form 0b01010101 . 然后bin(X)将其转换为格式为0b01010101的字符串。

The [2:] then gets rid of the 0b at the front and zfill(16) fills that out to 16 "bits". 然后[2:]摆脱前面的0bzfill(16)将其填充为16个“位”。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM