在python中将输入str转换为int [duplicate]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我收到错误代码:

在当前状态下'str'和'int'的实例之间不支持TypeError:'>'。

问题是我不知道如何将用户输入期望转换为字符串格式的整数。

number = input ("Please guess what number I'm thinking of. HINT: it's between 1 and 30")

我已经查找了如何做到这一点,但我找不到我要找的东西,因为我不确定如何正确地说出我的问题。

我曾尝试在int之后和number之后加入“input”,但它不起作用。不知道该把它放到哪里工作。

python math structure typeerror conventions
1个回答
2
投票

默认情况下,输入类型为string。要将它转换为integer,只需将int放在input之前。例如。

number = int(input("Please guess what number I'm thinking of. HINT: it's between 1 and 30: "))
print(type(number))

输出样本:

Please guess what number I'm thinking of. HINT: it's between 1 and 30: 30
<class 'int'>   # it shows that the input type is integer

备选

# any input is string
number = input("Please guess what number I'm thinking of. HINT: it's between 1 and 30: ")   
try:                      # if possible, try to convert the input into integer
    number = int(number)
except:                   # if the input couldn't be converted into integer, then do nothing
    pass
print(type(number))       # see the input type after processing

输出样本:

Please guess what number I'm thinking of. HINT: it's between 1 and 30: 25    # the input is a number 25
<class 'int'>   # 25 is possible to convert into integer. So, the type is integer

Please guess what number I'm thinking of. HINT: it's between 1 and 30: AAA   # the input is a number AAA
<class 'str'>   # AAA is impossible to convert into integer. So, the type remains string
© www.soinside.com 2019 - 2024. All rights reserved.