在 python 中将输入字符串转换为 int
Convert input str to int in python
我收到错误代码:
TypeError: '>' not supported between instances of 'str' and 'int' in
its current state.
问题是我不知道如何将用户输入期望值从字符串格式转换为整数。
number = input ("Please guess what number I'm thinking of. HINT: it's between 1 and 30")
我已经查看了如何操作,但找不到我要找的内容,因为我不确定如何正确表达我的问题。
我试过在 number
和 input
之后放置“int
”,但它不起作用。不知道把它放在哪里才能让它工作。
默认输入类型为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
我收到错误代码:
TypeError: '>' not supported between instances of 'str' and 'int' in its current state.
问题是我不知道如何将用户输入期望值从字符串格式转换为整数。
number = input ("Please guess what number I'm thinking of. HINT: it's between 1 and 30")
我已经查看了如何操作,但找不到我要找的内容,因为我不确定如何正确表达我的问题。
我试过在 number
和 input
之后放置“int
”,但它不起作用。不知道把它放在哪里才能让它工作。
默认输入类型为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