Python:从整数解析数字时抛出类型错误

问题描述 投票:0回答:4
two_digit_number = input()
yellow = int(two_digit_number)
print(type(yellow))
print(str(yellow[1]))

错误

<class 'int'>
Traceback (most recent call last):
  File "main.py", line 8, in <module>
    print(str(yellow[1]))
TypeError: 'int' object is not subscriptable

我在期待什么? 如果我的输入是34 我的输出应该是 4

python
4个回答
0
投票

此行 print(str(yellow[1])) 尝试通过索引访问数字,但该功能仅存在于字符串中,因为您已将输入转换为 int 此处 Yellow = int(two_digit_number) 使用这个变量代替two_digit_number[1]


0
投票

为了提高效率,您可以使用纯数学来解决这个问题,并且忘记昂贵的字符串操作。关键是使用模算术来本质上“剥离”要添加的个位数。

例如:

sum_ = 0
n = int(input('Enter a number: '))

while n > 0:
    # Accumulate the sum for each 'ones' digit.
    sum_ += n % 10
    # Divide N by 10 to 'strip off' the accumulated digit.
    n //= 10

print(f'Answer: {sum_}')

-1
投票

你的代码执行此操作

two_digit_number = input() # taking user input, string type
yellow = int(two_digit_number) # converting user input to int type
print(type(yellow)) # printing type of the variable yellow
print(str(yellow[1])) # indexing the integer, which is throwing error

如果你想获得输入的所有数字的总和,那么你需要迭代每个数字,将单个数字转换为 int 类型,然后将它们加在一起

下面的代码就是这样做的

two_digit_number = input()
digit_sum = 0 
for digit in two_digit_number:
    if digit.isdigit():
        digit_sum += int(digit)
    else:
        raise TypeError(f"expecting {digit} to be int type, found {type(digt)}")
print(digit_sum)

-3
投票

您更正后的代码如下:

two_digit_number = input()
yellow = int(two_digit_number)
print(type(yellow))
print(str(yellow)[1])

首先,str(yellow)会将变量yellow转换为字符串,然后您可以使用str(yellow)[1]为结果添加下标。这有点像内联投射和订阅。

它类似于基于类型转换的订阅,

two_digit_number = input()
yellow = int(two_digit_number)
print(type(yellow))
yellow = "{}".format(yellow) # or yellow=str(yellow)
print(yellow[1])
© www.soinside.com 2019 - 2024. All rights reserved.