【问题标题】:Python: 'int' object is not subscriptablePython:“int”对象不可下标
【发布时间】:2012-08-04 01:52:03
【问题描述】:

我在这里遇到了一个错误,我想知道你们中是否有人能看出我哪里出错了。我几乎是 python 的初学者,看不出哪里出错了。

temp = int(temp)^2/key
for i in range(0, len(str(temp))):
    final = final + chr(int(temp[i]))

“temp”由数字组成。 “钥匙”也是由数字组成的。这里有什么帮助吗?

【问题讨论】:

  • tempint,所以不能写temp[i]
  • final = final + chr(int(temp[i])) TypeError: 'int' object is not subscriptable
  • 我不确定你是否知道这一点,但是 num^2 并不意味着 num squared,它意味着 num xor 2。如果你想要一个幂,你必须使用 ** 运算符,即 int(temp)**2/key。如果您打算使用 xor,请忽略它。

标签: python object int


【解决方案1】:
final = final + chr(int(temp[i]))

在那一行 temp 仍然是一个数字,所以使用str(temp)[i]

编辑

>>> temp = 100  #number
>>> str(temp)[0] #convert temp to string and access i-th element
'1'
>>> int(str(temp)[0]) #convert character to int
1
>>> chr(int(str(temp)[0]))
'\x01'
>>> 

【讨论】:

  • final = final + chr(str(temp)[i]) 抛出:TypeError: an integer is required
【解决方案2】:

首先,您将temp 定义为一个整数(另外,在Python 中,^ 不是“电源”符号。您可能正在寻找**):

temp = int(temp)^2/key

但是你把它当作一个字符串:

chr(int(temp[i]))
        ^^^^^^^

是否还有另一个名为 temp 的字符串?或者您是否希望提取ith 数字,可以这样做:

str(temp)[i]

【讨论】:

  • 只是抛出:TypeError: an integer is required
  • @user1580845 是的,如果您不将 str(temp)[i] 调用包装在 int 调用中,这将引发错误,但无法给出更好的答案,因为目前还不清楚您在尝试什么去做。
  • 我正在尝试提取 temp 的 ith 数字,它是一个整数,并获取该数字所代表的字符并将其分配给一个字符串。
  • final = final + chr(int(temp[i])) 变为 final = final + chr(int(str(temp)[i]))。此外,final = final + ... 可以是 final+=
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 2015-07-31
  • 2012-04-04
  • 2012-01-03
  • 1970-01-01
相关资源
最近更新 更多